diff --git a/trilhas_poo/.gitignore b/trilhas_poo/.gitignore new file mode 100644 index 0000000..ad8c598 --- /dev/null +++ b/trilhas_poo/.gitignore @@ -0,0 +1,3 @@ +/vendor/ +composer.lock +.env \ No newline at end of file diff --git "a/trilhas_poo/DOCUMENTA\303\207\303\203O.md" "b/trilhas_poo/DOCUMENTA\303\207\303\203O.md" new file mode 100644 index 0000000..87d96eb --- /dev/null +++ "b/trilhas_poo/DOCUMENTA\303\207\303\203O.md" @@ -0,0 +1,121 @@ +# 📚 Trilha de Aprendizado: PHP Orientado a Objetos + +Este repositório documenta uma jornada prática de aprendizado em **PHP**, partindo dos conceitos fundamentais de **Programação Orientada a Objetos (POO)** até a implementação de arquiteturas utilizadas no mercado, como **Repository Pattern** e **Service Layer**. + +O objetivo da trilha é aplicar conceitos essenciais de orientação a objetos por meio de exercícios progressivos, construindo uma base sólida para o desenvolvimento de aplicações organizadas, escaláveis e de fácil manutenção. + +--- + +# 🎯 Estrutura de Branches + +O projeto foi dividido em branches para isolar cada etapa do aprendizado. Dessa forma, é possível acompanhar a evolução dos conceitos implementados. + +| Branch | Conteúdo | +| :------ | :------- | +| `master` | Base inicial do projeto. | +| `01_biblioteca` | Classes, Objetos, Encapsulamento e Construtores. | +| `02_funcionarios` | Herança, Classes Abstratas e Polimorfismo. | +| `03_pagamentos` | Interfaces e Polimorfismo. | +| `04_logger` | Utilização de Traits para reutilização de código. | +| `05_organizador` | Organização do projeto utilizando PSR-4, Namespaces e Autoload. | +| `06_Repository` | Implementação do padrão Repository para abstração da persistência. | +| `07_service` | Implementação da camada de Serviço (Service Layer). | +| `desafio` | Integração de todos os conceitos em um sistema completo. | + +--- + +# 📖 Conteúdo Programático + +## 1. Fundamentos e Organização + +### Encapsulamento +- Utilização dos modificadores de acesso (`private`, `protected` e `public`); +- Controle da visibilidade dos atributos e métodos. + +### Abstração +- Criação de classes abstratas; +- Definição e implementação de interfaces; +- Polimorfismo aplicado à orientação a objetos. + +### Organização com PSR-4 + +Organização completa do projeto utilizando **Composer**, **Namespaces** e **Autoload**, eliminando a necessidade de `require` manuais (com exceção do `vendor/autoload.php`). + +--- + +## 2. Padrões de Arquitetura + +### Repository Pattern + +Implementação de uma camada dedicada exclusivamente ao acesso e manipulação de dados, mantendo a lógica de persistência desacoplada das regras de negócio. + +### Service Layer + +Criação de uma camada responsável por: + +- Centralizar regras de negócio; +- Realizar validações; +- Orquestrar chamadas aos repositórios; +- Manter a aplicação desacoplada e organizada. + +--- + +## 3. Desafio Final: Sistema de Biblioteca + +Como conclusão da trilha, foi desenvolvido um sistema de biblioteca integrando todos os conceitos estudados. + +O projeto contempla: + +- Implementação da interface `Identificavel` pelas classes **Livro** e **Usuário**; +- Classe **Empréstimo** responsável por orquestrar o relacionamento entre as entidades; +- Utilização de **Traits** para logging centralizado; +- Aplicação dos princípios de responsabilidade única e separação de responsabilidades (SOLID); +- Organização em camadas utilizando **Repository** e **Service Layer**. + +--- + +# 🚀 Como navegar entre os exercícios + +Para acessar uma etapa específica da trilha, utilize o seguinte comando dentro da pasta do projeto: + +```bash +git switch nomeDaBranch +``` + +Substitua `nomeDaBranch` pela branch desejada. + +**Exemplo:** + +```bash +git switch 03_pagamentos +``` + +--- + +# 📝 Observações + +> **Exercício 5 (`05_organizador`)** +> +> Nesta etapa, o foco foi a organização rigorosa da estrutura do projeto utilizando o padrão **PSR-4**. Cada classe foi separada em arquivos individuais dentro da pasta `src/`, seguindo a convenção adotada para facilitar o mapeamento automático realizado pelo Composer e tornar a estrutura mais clara e escalável. + +--- + +# 📌 Conceitos abordados + +- Classes e Objetos +- Encapsulamento +- Construtores +- Herança +- Classes Abstratas +- Interfaces +- Polimorfismo +- Traits +- Namespaces +- Composer +- PSR-4 +- Autoload +- Repository Pattern +- Service Layer +- Organização em Camadas +- Princípios SOLID +``` \ No newline at end of file diff --git a/trilhas_poo/composer.json b/trilhas_poo/composer.json new file mode 100644 index 0000000..f89f16f --- /dev/null +++ b/trilhas_poo/composer.json @@ -0,0 +1,29 @@ +{ + "name": "ana/trilhas_poo", + "autoload": { + "psr-4": { + "App\\": "src/" + } + }, + "authors": [ + { + "name": "Ana Beatriz", + "email": "ana.beatriz.adriano.silva.1929@gmail.com" + } + ], + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.95" + }, + "scripts": { + "format": "php-cs-fixer fix --allow-risky=yes --sequential", + "format:check": "php-cs-fixer fix --dry-run --diff --allow-risky=yes --sequential", + "test:basic": "php tests/ServiceTest.php", + "test:integration": "php tests/IntegrationTest.php", + "test:http": "php tests/HttpResponseTest.php", + "test": [ + "@test:basic", + "@test:integration", + "@test:http" + ] + } +} \ No newline at end of file diff --git a/trilhas_poo/composer.lock b/trilhas_poo/composer.lock new file mode 100644 index 0000000..a75bb63 --- /dev/null +++ b/trilhas_poo/composer.lock @@ -0,0 +1,2856 @@ +{ + "_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": "645796bb26c131e8fb0dbbf76b217216", + "packages": [], + "packages-dev": [ + { + "name": "clue/ndjson-react", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/clue/reactphp-ndjson.git", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/reactphp-ndjson/zipball/392dc165fce93b5bb5c637b67e59619223c931b0", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/stream": "^1.2" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react/event-loop": "^1.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "Clue\\React\\NDJson\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "homepage": "https://github.com/clue/reactphp-ndjson", + "keywords": [ + "NDJSON", + "json", + "jsonlines", + "newline", + "reactphp", + "streaming" + ], + "support": { + "issues": "https://github.com/clue/reactphp-ndjson/issues", + "source": "https://github.com/clue/reactphp-ndjson/tree/v1.3.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "time": "2022-12-23T10:58:28+00:00" + }, + { + "name": "composer/pcre", + "version": "3.4.0", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "d5a341b3fb61f3001970940afb1d332968a183ed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/d5a341b3fb61f3001970940afb1d332968a183ed", + "reference": "d5a341b3fb61f3001970940afb1d332968a183ed", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<2.2.2" + }, + "require-dev": { + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^9" + }, + "type": "library", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + }, + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.4.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "time": "2026-06-07T11:47:49+00:00" + }, + { + "name": "composer/semver", + "version": "3.4.4", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.4" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "time": "2025-08-20T19:15:30+00:00" + }, + { + "name": "composer/xdebug-handler", + "version": "3.0.5", + "source": { + "type": "git", + "url": "https://github.com/composer/xdebug-handler.git", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/6c1925561632e83d60a44492e0b344cf48ab85ef", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef", + "shasum": "" + }, + "require": { + "composer/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "phpunit/phpunit": "^8.5 || ^9.6 || ^10.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/3.0.5" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-05-06T16:37:16+00:00" + }, + { + "name": "ergebnis/agent-detector", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/ergebnis/agent-detector.git", + "reference": "e211f17928c8b95a51e06040792d57f5462fb271" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ergebnis/agent-detector/zipball/e211f17928c8b95a51e06040792d57f5462fb271", + "reference": "e211f17928c8b95a51e06040792d57f5462fb271", + "shasum": "" + }, + "require": { + "php": "~7.4.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.51.0", + "ergebnis/license": "^2.7.0", + "ergebnis/php-cs-fixer-config": "^6.60.2", + "ergebnis/phpstan-rules": "^2.13.1", + "ergebnis/phpunit-slow-test-detector": "^2.24.0", + "ergebnis/rector-rules": "^1.18.1", + "fakerphp/faker": "^1.24.1", + "infection/infection": "^0.26.6", + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^2.1.54", + "phpstan/phpstan-deprecation-rules": "^2.0.4", + "phpstan/phpstan-phpunit": "^2.0.16", + "phpstan/phpstan-strict-rules": "^2.0.10", + "phpunit/phpunit": "^9.6.34", + "rector/rector": "^2.4.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + }, + "composer-normalize": { + "indent-size": 2, + "indent-style": "space" + } + }, + "autoload": { + "psr-4": { + "Ergebnis\\AgentDetector\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Andreas Möller", + "email": "am@localheinz.com", + "homepage": "https://localheinz.com" + } + ], + "description": "Provides a detector for detecting the presence of an agent.", + "homepage": "https://github.com/ergebnis/agent-detector", + "support": { + "issues": "https://github.com/ergebnis/agent-detector/issues", + "security": "https://github.com/ergebnis/agent-detector/blob/main/.github/SECURITY.md", + "source": "https://github.com/ergebnis/agent-detector" + }, + "time": "2026-05-07T08:19:07+00:00" + }, + { + "name": "evenement/evenement", + "version": "v3.0.2", + "source": { + "type": "git", + "url": "https://github.com/igorw/evenement.git", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/igorw/evenement/zipball/0a16b0d71ab13284339abb99d9d2bd813640efbc", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^9 || ^6" + }, + "type": "library", + "autoload": { + "psr-4": { + "Evenement\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https://github.com/igorw/evenement/issues", + "source": "https://github.com/igorw/evenement/tree/v3.0.2" + }, + "time": "2023-08-08T05:53:35+00:00" + }, + { + "name": "fidry/cpu-core-counter", + "version": "1.3.0", + "source": { + "type": "git", + "url": "https://github.com/theofidry/cpu-core-counter.git", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry/makefile": "^0.2.0", + "fidry/php-cs-fixer-config": "^1.1.2", + "phpstan/extension-installer": "^1.2.0", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-deprecation-rules": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^8.5.31 || ^9.5.26", + "webmozarts/strict-phpunit": "^7.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Fidry\\CpuCoreCounter\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Tiny utility to get the number of CPU cores.", + "keywords": [ + "CPU", + "core" + ], + "support": { + "issues": "https://github.com/theofidry/cpu-core-counter/issues", + "source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0" + }, + "funding": [ + { + "url": "https://github.com/theofidry", + "type": "github" + } + ], + "time": "2025-08-14T07:29:31+00:00" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.95.15", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "3e47e5d50046f87e3244acde2fe655d1a3b72555" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/3e47e5d50046f87e3244acde2fe655d1a3b72555", + "reference": "3e47e5d50046f87e3244acde2fe655d1a3b72555", + "shasum": "" + }, + "require": { + "clue/ndjson-react": "^1.3", + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.5", + "ergebnis/agent-detector": "^1.2", + "ext-filter": "*", + "ext-hash": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "fidry/cpu-core-counter": "^1.3", + "php": "^7.4 || ^8.0", + "react/child-process": "^0.6.6", + "react/event-loop": "^1.5", + "react/socket": "^1.16", + "react/stream": "^1.4", + "sebastian/diff": "^4.0.6 || ^5.1.1 || ^6.0.2 || ^7.0 || ^8.0 || ^9.0", + "symfony/console": "^5.4.47 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/event-dispatcher": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/filesystem": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/finder": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/options-resolver": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/polyfill-mbstring": "^1.37", + "symfony/polyfill-php80": "^1.37", + "symfony/polyfill-php81": "^1.37", + "symfony/polyfill-php84": "^1.37", + "symfony/process": "^5.4.47 || ^6.4.24 || ^7.2 || ^8.0", + "symfony/stopwatch": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3.1 || ^2.11.0", + "infection/infection": "^0.32.7", + "justinrainbow/json-schema": "^6.10.0", + "keradus/cli-executor": "^2.3", + "mikey179/vfsstream": "^1.6.12", + "php-coveralls/php-coveralls": "^2.9.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.8", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.8", + "phpunit/phpunit": "^9.6.35 || ^10.5.64 || ^11.5.56 || ^12.5.31", + "symfony/polyfill-php85": "^1.38", + "symfony/var-dumper": "^5.4.48 || ^6.4.36 || ^7.4.8 || ^8.1.0", + "symfony/yaml": "^5.4.53 || ^6.4.41 || ^7.4.13 || ^8.1.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + }, + "exclude-from-classmap": [ + "src/**/Internal/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.15" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "time": "2026-07-15T09:51:47+00:00" + }, + { + "name": "psr/container", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "time": "2021-11-05T16:47:00+00:00" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "time": "2019-01-08T18:20:26+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "react/cache", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/cache.git", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/cache/zipball/d47c472b64aa5608225f47965a484b75c7817d5b", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/cache/issues", + "source": "https://github.com/reactphp/cache/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2022-11-30T15:59:55+00:00" + }, + { + "name": "react/child-process", + "version": "v0.6.7", + "source": { + "type": "git", + "url": "https://github.com/reactphp/child-process.git", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/child-process/zipball/970f0e71945556422ee4570ccbabaedc3cf04ad3", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/event-loop": "^1.2", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/socket": "^1.16", + "sebastian/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\ChildProcess\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": [ + "event-driven", + "process", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/child-process/issues", + "source": "https://github.com/reactphp/child-process/tree/v0.6.7" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-12-23T15:25:20+00:00" + }, + { + "name": "react/dns", + "version": "v1.14.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/dns.git", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/dns/zipball/7562c05391f42701c1fccf189c8225fece1cd7c3", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3 || ^2", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Dns\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/dns/issues", + "source": "https://github.com/reactphp/dns/tree/v1.14.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-18T19:34:28+00:00" + }, + { + "name": "react/event-loop", + "version": "v1.6.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/event-loop.git", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/event-loop/zipball/ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https://github.com/reactphp/event-loop/issues", + "source": "https://github.com/reactphp/event-loop/tree/v1.6.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-17T20:46:25+00:00" + }, + { + "name": "react/promise", + "version": "v3.3.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise.git", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise/zipball/23444f53a813a3296c1368bb104793ce8d88f04a", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a", + "shasum": "" + }, + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan/phpstan": "1.12.28 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^7.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "React\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https://github.com/reactphp/promise/issues", + "source": "https://github.com/reactphp/promise/tree/v3.3.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-08-19T18:57:03+00:00" + }, + { + "name": "react/socket", + "version": "v1.17.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/socket.git", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/socket/zipball/ef5b17b81f6f60504c539313f94f2d826c5faa08", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/dns": "^1.13", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.6 || ^1.2.1", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3.3 || ^2", + "react/promise-stream": "^1.4", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Socket\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https://github.com/reactphp/socket/issues", + "source": "https://github.com/reactphp/socket/tree/v1.17.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-19T20:47:34+00:00" + }, + { + "name": "react/stream", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/stream.git", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/stream/zipball/1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react/event-loop": "^1.2" + }, + "require-dev": { + "clue/stream-filter": "~1.2", + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Stream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https://github.com/reactphp/stream/issues", + "source": "https://github.com/reactphp/stream/tree/v1.4.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2024-06-11T12:45:25+00:00" + }, + { + "name": "sebastian/diff", + "version": "9.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/a3fb6a298a265ff487a91bbea46e03cd01dbb226", + "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226", + "shasum": "" + }, + "require": { + "php": ">=8.4" + }, + "require-dev": { + "phpunit/phpunit": "^13.2", + "symfony/process": "^7.4.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "9.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/9.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/diff", + "type": "tidelift" + } + ], + "time": "2026-06-05T03:04:51+00:00" + }, + { + "name": "symfony/console", + "version": "v8.1.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d", + "reference": "b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php85": "^1.32", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^7.4.6|^8.0.6" + }, + "conflict": { + "symfony/dependency-injection": "<8.1", + "symfony/event-dispatcher": "<8.1" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^7.4|^8.0", + "symfony/dependency-injection": "^8.1", + "symfony/event-dispatcher": "^8.1", + "symfony/filesystem": "^7.4|^8.0", + "symfony/http-foundation": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/lock": "^7.4|^8.0", + "symfony/messenger": "^7.4|^8.0", + "symfony/mime": "^7.4|^8.0", + "symfony/process": "^7.4|^8.0", + "symfony/stopwatch": "^7.4|^8.0", + "symfony/uid": "^7.4|^8.0", + "symfony/validator": "^7.4|^8.0", + "symfony/var-dumper": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-16T12:55:20+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.7.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "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.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-05T06:23:12+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v8.1.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "abd6c11dc468725d1627302ad10f6cd486e9e3d0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/abd6c11dc468725d1627302ad10f6cd486e9e3d0", + "reference": "abd6c11dc468725d1627302ad10f6cd486e9e3d0", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/security-http": "<7.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^7.4|^8.0", + "symfony/dependency-injection": "^7.4|^8.0", + "symfony/error-handler": "^7.4|^8.0", + "symfony/expression-language": "^7.4|^8.0", + "symfony/framework-bundle": "^7.4|^8.0", + "symfony/http-foundation": "^7.4|^8.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-09T12:28:30+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.7.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-05T06:23:12+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/99aec13b82b4967ec5088222c4a3ecca955949c2", + "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "require-dev": { + "symfony/process": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-29T05:06:50+00:00" + }, + { + "name": "symfony/finder", + "version": "v8.1.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/e2989e762c70f9490fa3a00a0ac0fae5aa97a531", + "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531", + "shasum": "" + }, + "require": { + "php": ">=8.4.1" + }, + "require-dev": { + "symfony/filesystem": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-27T09:05:56+00:00" + }, + { + "name": "symfony/options-resolver", + "version": "v8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "88f9c561f678a02d54b897014049fa839e33ff82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/88f9c561f678a02d54b897014049fa839e33ff82", + "reference": "88f9c561f678a02d54b897014049fa839e33ff82", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-29T05:06:50+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.37.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-04-10T16:19:22+00:00" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.38.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "e9247d281d694a5120554d9afaf54e070e88a603" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/e9247d281d694a5120554d9afaf54e070e88a603", + "reference": "e9247d281d694a5120554d9afaf54e070e88a603", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-26T05:58:03+00:00" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.38.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/2d446c214bdbe5b71bde5011b060a05fece3ae6b", + "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.38.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-25T13:48:31+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.38.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", + "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.38.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-27T06:59:30+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.37.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-04-10T16:19:22+00:00" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.38.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "6bfb9c766cacffbc8e118cb87217d08ed84e5cd7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/6bfb9c766cacffbc8e118cb87217d08ed84e5cd7", + "reference": "6bfb9c766cacffbc8e118cb87217d08ed84e5cd7", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-26T12:45:58+00:00" + }, + { + "name": "symfony/polyfill-php84", + "version": "v1.38.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php84.git", + "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa", + "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php84\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.4+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php84/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-26T12:51:13+00:00" + }, + { + "name": "symfony/polyfill-php85", + "version": "v1.38.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php85.git", + "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1", + "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php85\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.5+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php85/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-26T02:25:22+00:00" + }, + { + "name": "symfony/process", + "version": "v8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/c4a9e58f235a6bf7f97ffbfedae2687353ac79e5", + "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5", + "shasum": "" + }, + "require": { + "php": ">=8.4.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-29T05:06:50+00:00" + }, + { + "name": "symfony/service-contracts", + "version": "v3.7.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/c0a284bab1ed8aa0417e3d69250ab437739563a0", + "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-16T09:55:08+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "21c07b026905d596e8379caeb115d87aa479499d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/21c07b026905d596e8379caeb115d87aa479499d", + "reference": "21c07b026905d596e8379caeb115d87aa479499d", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/service-contracts": "^2.5|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-29T05:06:50+00:00" + }, + { + "name": "symfony/string", + "version": "v8.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/afd5944f4005862d961efb85c8bbd5c523c4e3c9", + "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-intl-grapheme": "^1.33", + "symfony/polyfill-intl-normalizer": "^1.0", + "symfony/polyfill-mbstring": "^1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/emoji": "^7.4|^8.0", + "symfony/http-client": "^7.4|^8.0", + "symfony/intl": "^7.4|^8.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-29T05:06:50+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/trilhas_poo/docker-compose.yml b/trilhas_poo/docker-compose.yml new file mode 100644 index 0000000..d4fa68f --- /dev/null +++ b/trilhas_poo/docker-compose.yml @@ -0,0 +1,33 @@ +services: + php: + build: + context: . + dockerfile: docker/php/Dockerfile + container_name: trilha-poo-php + working_dir: /var/www + volumes: + - ./:/var/www + env_file: + - .env + ports: + - "8000:8000" + command: php -S 0.0.0.0:8000 -t public + stdin_open: true + tty: true + depends_on: + - postgres + + postgres: + image: postgres:17 + container_name: trilha-poo-pgsql + environment: + POSTGRES_DB: trilha_poo + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + +volumes: + postgres_data: \ No newline at end of file diff --git a/trilhas_poo/docker/php/Dockerfile b/trilhas_poo/docker/php/Dockerfile new file mode 100644 index 0000000..7da8fc0 --- /dev/null +++ b/trilhas_poo/docker/php/Dockerfile @@ -0,0 +1,11 @@ +FROM php:8.4-cli + +RUN apt-get update && apt-get install -y \ + git \ + unzip \ + libpq-dev \ + && docker-php-ext-install pdo pdo_pgsql + +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + +WORKDIR /var/www \ No newline at end of file diff --git a/trilhas_poo/docker/postgres/init.sql b/trilhas_poo/docker/postgres/init.sql new file mode 100644 index 0000000..e69de29 diff --git a/trilhas_poo/public/assets/css/style.css b/trilhas_poo/public/assets/css/style.css new file mode 100644 index 0000000..d4ab102 --- /dev/null +++ b/trilhas_poo/public/assets/css/style.css @@ -0,0 +1,219 @@ +:root{ + --background:#111827; + --surface:#1f2937; + --surface-light:#273447; + + --border:#374151; + + --primary:#3b82f6; + --secondary:#9745f5; + + --text:#f9fafb; + --muted:#9ca3af; + + --success:#22c55e; +} + +*{ + margin:0; + padding:0; + box-sizing:border-box; +} + +body{ + background:var(--background); + color:var(--text); + font-family:Inter,Segoe UI,Arial,sans-serif; +} + +.container{ + width:min(1200px,92%); + margin:auto; +} + +header{ + border-bottom:1px solid var(--border); + background:#182231; +} + +.navbar{ + display:flex; + justify-content:space-between; + align-items:center; + padding:32px 0; +} + +header h1{ + font-size:2.3rem; + margin:12px 0; +} + +header p{ + color:var(--muted); + max-width:700px; + line-height:1.6; +} + +.badge{ + display:inline-block; + background:rgba(59,130,246,.15); + color:#93c5fd; + padding:8px 14px; + border-radius:50px; + font-size:.85rem; +} + +.status{ + display:flex; + align-items:center; + gap:10px; + color:var(--muted); +} + +.dot{ + width:10px; + height:10px; + border-radius:50%; + background:var(--success); + box-shadow:0 0 10px var(--success); +} + +.hero{ + margin:60px 0; + display:grid; + grid-template-columns:2fr 1fr; + gap:30px; +} + +.hero-text h2{ + font-size:2rem; + margin-bottom:20px; +} + +.hero-text p{ + color:var(--muted); + line-height:1.8; +} + +.buttons{ + margin-top:30px; + display:flex; + gap:15px; +} + +.btn{ + text-decoration:none; + color:white; + border:1px solid var(--border); + padding:12px 20px; + border-radius:10px; + transition:.2s; +} + +.btn:hover{ + background:var(--surface); +} + +.primary{ + background:var(--primary); + border:none; +} + +.secondary{ + background:var(--secondary); + border:none; +} + +.primary:hover{ + opacity:.9; +} + +.hero-card{ + background:var(--surface); + border:1px solid var(--border); + border-radius:16px; + padding:24px; +} + +.hero-card h3{ + margin-bottom:20px; +} + +.progress{ + width:100%; + height:12px; + background:#374151; + border-radius:999px; + overflow:hidden; + margin-bottom:15px; +} + +.progress-bar{ + width:35%; + height:100%; + background:linear-gradient(90deg,#3b82f6,#60a5fa); +} + +.grid{ + display:grid; + grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); + gap:25px; +} + +.card{ + background:var(--surface); + border:1px solid var(--border); + border-radius:16px; + padding:24px; + transition:.2s; +} + +.card:hover{ + transform:translateY(-4px); + border-color:#4b5563; +} + +.card h3{ + margin-bottom:18px; +} + +.card p, +.card li{ + color:var(--muted); + line-height:1.8; +} + +.card ul{ + padding-left:20px; +} + +.tags{ + display:flex; + flex-wrap:wrap; + gap:10px; +} + +.tags span{ + background:var(--surface-light); + padding:8px 12px; + border-radius:8px; + font-size:.9rem; +} + +footer{ + margin:80px 0 30px; + text-align:center; + color:var(--muted); +} + +@media(max-width:900px){ + .hero{ + grid-template-columns:1fr; + } + + .navbar{ + flex-direction:column; + align-items:flex-start; + gap:25px; + } +} \ No newline at end of file diff --git a/trilhas_poo/public/index.php b/trilhas_poo/public/index.php new file mode 100644 index 0000000..4f421bd --- /dev/null +++ b/trilhas_poo/public/index.php @@ -0,0 +1,106 @@ + + + + + + + Trilha POO | Sistema de Gestão de Transportadora + + + +
+ +
+
+
+
+

Bem-vindo(a) à Trilha POO

+

+ Este projeto reúne todos os conceitos estudados ao longo da trilha, + aplicando Programação Orientada a Objetos em uma aplicação completa. +

+ +
+
+

Status do Projeto

+
+
+
+ Estrutura inicial concluída. +
+
+
+
+

Ambiente

+
    + +
  • + +
+
+
+

Arquitetura

+
+ POO + Repository + Service + PDO + Docker + PostgreSQL +
+
+
+

Conteúdo

+
    +
  • Classes
  • +
  • Herança
  • +
  • Interfaces
  • +
  • Traits
  • +
  • Repository Pattern
  • +
  • Service Layer
  • +
+
+
+

Objetivo

+

+ Desenvolver um sistema completo de gestão de transportadora + utilizando boas práticas de desenvolvimento e arquitetura em PHP. +

+
+
+
+ + + \ No newline at end of file diff --git a/trilhas_poo/src/Repositories/a b/trilhas_poo/src/Repositories/a new file mode 100644 index 0000000..e69de29 diff --git a/trilhas_poo/src/Services/a b/trilhas_poo/src/Services/a new file mode 100644 index 0000000..e69de29 diff --git a/trilhas_poo/vendor/autoload.php b/trilhas_poo/vendor/autoload.php new file mode 100644 index 0000000..f3581b0 --- /dev/null +++ b/trilhas_poo/vendor/autoload.php @@ -0,0 +1,22 @@ +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__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer'); + } +} + +return include __DIR__ . '/..'.'/friendsofphp/php-cs-fixer/php-cs-fixer'; diff --git a/trilhas_poo/vendor/clue/ndjson-react/.github/FUNDING.yml b/trilhas_poo/vendor/clue/ndjson-react/.github/FUNDING.yml new file mode 100644 index 0000000..9c09fb8 --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: clue +custom: https://clue.engineering/support diff --git a/trilhas_poo/vendor/clue/ndjson-react/CHANGELOG.md b/trilhas_poo/vendor/clue/ndjson-react/CHANGELOG.md new file mode 100644 index 0000000..bc4faf6 --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog + +## 1.3.0 (2022-12-23) + +* Feature: Add support for PHP 8.1 and PHP 8.2. + (#31 by @clue and #30 by @SimonFring) + +* Feature: Check type of incoming `data` before trying to decode NDJSON. + (#29 by @SimonFrings) + +* Improve documentation and examples and update to new [default loop](https://reactphp.org/event-loop/#loop). + (#26 by @clue, #27 by @SimonFrings and #25 by @PaulRotmann) + +* Improve test suite, report failed assertions and ensure 100% code coverage. + (#32 and #33 by @clue and #28 by @SimonFrings) + +## 1.2.0 (2020-12-09) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Add PHP 8 support, update to PHPUnit 9 and simplify test setup. + (#18 by @clue and #19, #22 and #23 by @SimonFrings) + +## 1.1.0 (2020-02-04) + +* Feature: Improve error reporting and add parsing error message to Exception and + ignore `JSON_THROW_ON_ERROR` option (available as of PHP 7.3). + (#14 by @clue) + +* Feature: Add bechmarking script and import all global function references. + (#16 by @clue) + +* Improve documentation and add NDJSON format description and + add support / sponsorship info. + (#12 and #17 by @clue) + +* Improve test suite to run tests on PHP 7.4 and simplify test matrix and + apply minor code style adjustments to make phpstan happy. + (#13 and #15 by @clue) + +## 1.0.0 (2018-05-17) + +* First stable release, now following SemVer + +* Improve documentation and usage examples + +> Contains no other changes, so it's actually fully compatible with the v0.1.2 release. + +## 0.1.2 (2018-05-11) + +* Feature: Limit buffer size to 64 KiB by default. + (#10 by @clue) + +* Feature: Forward compatiblity with EventLoop v0.5 and upcoming v1.0. + (#8 by @clue) + +* Fix: Return bool `false` if encoding fails due to invalid value to pause source. + (#9 by @clue) + +* Improve test suite by supporting PHPUnit v6 and test against legacy PHP 5.3 through PHP 7.2. + (#7 by @clue) + +* Update project homepage. + (#11 by @clue) + +## 0.1.1 (2017-05-22) + +* Feature: Forward compatibility with Stream v0.7, v0.6, v0.5 and upcoming v1.0 (while keeping BC) + (#6 by @thklein) + +* Improved test suite by adding PHPUnit to `require-dev` + (#5 by @thklein) + +## 0.1.0 (2016-11-24) + +* First tagged release diff --git a/trilhas_poo/vendor/clue/ndjson-react/LICENSE b/trilhas_poo/vendor/clue/ndjson-react/LICENSE new file mode 100644 index 0000000..7baae8e --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Christian Lück + +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/trilhas_poo/vendor/clue/ndjson-react/README.md b/trilhas_poo/vendor/clue/ndjson-react/README.md new file mode 100644 index 0000000..0ca4eab --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/README.md @@ -0,0 +1,365 @@ +# clue/reactphp-ndjson + +[![CI status](https://github.com/clue/reactphp-ndjson/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-ndjson/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/clue/ndjson-react?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/ndjson-react) +[![code coverage](https://img.shields.io/badge/code%20coverage-100%25-success)](#tests) + +Streaming newline-delimited JSON ([NDJSON](http://ndjson.org/)) parser and encoder for [ReactPHP](https://reactphp.org/). + +[NDJSON](http://ndjson.org/) can be used to store multiple JSON records in a +file to store any kind of (uniform) structured data, such as a list of user +objects or log entries. It uses a simple newline character between each +individual record and as such can be both used for efficient persistence and +simple append-style operations. This also allows it to be used in a streaming +context, such as a simple inter-process communication (IPC) protocol or for a +remote procedure call (RPC) mechanism. This library provides a simple +streaming API to process very large NDJSON files with thousands or even millions +of rows efficiently without having to load the whole file into memory at once. + +* **Standard interfaces** - + Allows easy integration with existing higher-level components by implementing + ReactPHP's standard streaming interfaces. +* **Lightweight, SOLID design** - + Provides a thin abstraction that is [*just good enough*](https://en.wikipedia.org/wiki/Principle_of_good_enough) + and does not get in your way. + Builds on top of well-tested components and well-established concepts instead of reinventing the wheel. +* **Good test coverage** - + Comes with an [automated tests suite](#tests) and is regularly tested in the *real world*. + +**Table of contents** + +* [Support us](#support-us) +* [NDJSON format](#ndjson-format) +* [Usage](#usage) + * [Decoder](#decoder) + * [Encoder](#encoder) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Support us + +We invest a lot of time developing, maintaining, and updating our awesome +open-source projects. You can help us sustain this high-quality of our work by +[becoming a sponsor on GitHub](https://github.com/sponsors/clue). Sponsors get +numerous benefits in return, see our [sponsoring page](https://github.com/sponsors/clue) +for details. + +Let's take these projects to the next level together! 🚀 + +## NDJSON format + +NDJSON ("Newline-Delimited JSON" or sometimes referred to as "JSON lines") is a +very simple text-based format for storing a large number of records, such as a +list of user records or log entries. + +```JSON +{"name":"Alice","age":30,"comment":"Yes, I like cheese"} +{"name":"Bob","age":50,"comment":"Hello\nWorld!"} +``` + +If you understand JSON and you're now looking at this newline-delimited JSON for +the first time, you should already know everything you need to know to +understand NDJSON: As the name implies, this format essentially consists of +individual lines where each individual line is any valid JSON text and each line +is delimited with a newline character. + +This example uses a list of user objects where each user has some arbitrary +properties. This can easily be adjusted for many different use cases, such as +storing for example products instead of users, assigning additional properties +or having a significantly larger number of records. You can edit NDJSON files in +any text editor or use them in a streaming context where individual records +should be processed. Unlike normal JSON files, adding a new log entry to this +NDJSON file does not require modification of this file's structure (note there's +no "outer array" to be modified). This makes it a perfect fit for a streaming +context, for line-oriented CLI tools (such as `grep` and others) or for a logging +context where you want to append records at a later time. Additionally, this +also allows it to be used in a streaming context, such as a simple inter-process +communication (IPC) protocol or for a remote procedure call (RPC) mechanism. + +The newline character at the end of each line allows for some really simple +*framing* (detecting individual records). While each individual line is valid +JSON, the complete file as a whole is technically no longer valid JSON, because +it contains multiple JSON texts. This implies that for example calling PHP's +`json_decode()` on this complete input would fail because it would try to parse +multiple records at once. Likewise, using "pretty printing" JSON +(`JSON_PRETTY_PRINT`) is not allowed because each JSON text is limited to exactly +one line. On the other hand, values containing newline characters (such as the +`comment` property in the above example) do not cause issues because each newline +within a JSON string will be represented by a `\n` instead. + +One common alternative to NDJSON would be Comma-Separated Values (CSV). +If you want to process CSV files, you may want to take a look at the related +project [clue/reactphp-csv](https://github.com/clue/reactphp-csv) instead: + +``` +name,age,comment +Alice,30,"Yes, I like cheese" +Bob,50,"Hello +World!" +``` + +CSV may look slightly simpler, but this simplicity comes at a price. CSV is +limited to untyped, two-dimensional data, so there's no standard way of storing +any nested structures or to differentiate a boolean value from a string or +integer. Field names are sometimes used, sometimes they're not +(application-dependant). Inconsistent handling for fields that contain +separators such as `,` or spaces or line breaks (see the `comment` field above) +introduce additional complexity and its text encoding is usually undefined, +Unicode (or UTF-8) is unlikely to be supported and CSV files often use ISO +8859-1 encoding or some variant (again application-dependant). + +While NDJSON helps avoiding many of CSV's shortcomings, it is still a +(relatively) young format while CSV files have been used in production systems +for decades. This means that if you want to interface with an existing system, +you may have to rely on the format that's already supported. If you're building +a new system, using NDJSON is an excellent choice as it provides a flexible way +to process individual records using a common text-based format that can include +any kind of structured data. + +## Usage + +### Decoder + +The `Decoder` (parser) class can be used to make sure you only get back +complete, valid JSON elements when reading from a stream. +It wraps a given +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +and exposes its data through the same interface, but emits the JSON elements +as parsed values instead of just chunks of strings: + +``` +{"name":"test","active":true} +{"name":"hello w\u00f6rld","active":true} +``` + +```php +$stdin = new React\Stream\ReadableResourceStream(STDIN); + +$ndjson = new Clue\React\NDJson\Decoder($stdin); + +$ndjson->on('data', function ($data) { + // $data is a parsed element from the JSON stream + // line 1: $data = (object)array('name' => 'test', 'active' => true); + // line 2: $data = (object)array('name' => 'hello wörld', 'active' => true); + var_dump($data); +}); +``` + +ReactPHP's streams emit chunks of data strings and make no assumption about their lengths. +These chunks do not necessarily represent complete JSON elements, as an +element may be broken up into multiple chunks. +This class reassembles these elements by buffering incomplete ones. + +The `Decoder` supports the same optional parameters as the underlying +[`json_decode()`](https://www.php.net/manual/en/function.json-decode.php) function. +This means that, by default, JSON objects will be emitted as a `stdClass`. +This behavior can be controlled through the optional constructor parameters: + +```php +$ndjson = new Clue\React\NDJson\Decoder($stdin, true); + +$ndjson->on('data', function ($data) { + // JSON objects will be emitted as assoc arrays now +}); +``` + +Additionally, the `Decoder` limits the maximum buffer size (maximum line +length) to avoid buffer overflows due to malformed user input. Usually, there +should be no need to change this value, unless you know you're dealing with some +unreasonably long lines. It accepts an additional argument if you want to change +this from the default of 64 KiB: + +```php +$ndjson = new Clue\React\NDJson\Decoder($stdin, false, 512, 0, 64 * 1024); +``` + +If the underlying stream emits an `error` event or the plain stream contains +any data that does not represent a valid NDJson stream, +it will emit an `error` event and then `close` the input stream: + +```php +$ndjson->on('error', function (Exception $error) { + // an error occured, stream will close next +}); +``` + +If the underlying stream emits an `end` event, it will flush any incomplete +data from the buffer, thus either possibly emitting a final `data` event +followed by an `end` event on success or an `error` event for +incomplete/invalid JSON data as above: + +```php +$ndjson->on('end', function () { + // stream successfully ended, stream will close next +}); +``` + +If either the underlying stream or the `Decoder` is closed, it will forward +the `close` event: + +```php +$ndjson->on('close', function () { + // stream closed + // possibly after an "end" event or due to an "error" event +}); +``` + +The `close(): void` method can be used to explicitly close the `Decoder` and +its underlying stream: + +```php +$ndjson->close(); +``` + +The `pipe(WritableStreamInterface $dest, array $options = array(): WritableStreamInterface` +method can be used to forward all data to the given destination stream. +Please note that the `Decoder` emits decoded/parsed data events, while many +(most?) writable streams expect only data chunks: + +```php +$ndjson->pipe($logger); +``` + +For more details, see ReactPHP's +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface). + +### Encoder + +The `Encoder` (serializer) class can be used to make sure anything you write to +a stream ends up as valid JSON elements in the resulting NDJSON stream. +It wraps a given +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface) +and accepts its data through the same interface, but handles any data as complete +JSON elements instead of just chunks of strings: + +```php +$stdout = new React\Stream\WritableResourceStream(STDOUT); + +$ndjson = new Clue\React\NDJson\Encoder($stdout); + +$ndjson->write(array('name' => 'test', 'active' => true)); +$ndjson->write(array('name' => 'hello wörld', 'active' => true)); +``` +``` +{"name":"test","active":true} +{"name":"hello w\u00f6rld","active":true} +``` + +The `Encoder` supports the same parameters as the underlying +[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php) function. +This means that, by default, Unicode characters will be escaped in the output. +This behavior can be controlled through the optional constructor parameters: + +```php +$ndjson = new Clue\React\NDJson\Encoder($stdout, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + +$ndjson->write('hello wörld'); +``` +``` +"hello wörld" +``` + +Note that trying to pass the `JSON_PRETTY_PRINT` option will yield an +`InvalidArgumentException` because it is not compatible with NDJSON. + +If the underlying stream emits an `error` event or the given data contains +any data that can not be represented as a valid NDJSON stream, +it will emit an `error` event and then `close` the input stream: + +```php +$ndjson->on('error', function (Exception $error) { + // an error occured, stream will close next +}); +``` + +If either the underlying stream or the `Encoder` is closed, it will forward +the `close` event: + +```php +$ndjson->on('close', function () { + // stream closed + // possibly after an "end" event or due to an "error" event +}); +``` + +The `end(mixed $data = null): void` method can be used to optionally emit +any final data and then soft-close the `Encoder` and its underlying stream: + +```php +$ndjson->end(); +``` + +The `close(): void` method can be used to explicitly close the `Encoder` and +its underlying stream: + +```php +$ndjson->close(); +``` + +For more details, see ReactPHP's +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface). + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require clue/ndjson-react:^1.3 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +This project is released under the permissive [MIT license](LICENSE). + +> Did you know that I offer custom development services and issuing invoices for + sponsorships of releases and for contributions? Contact me (@clue) for details. + +## More + +* If you want to learn more about processing streams of data, refer to the documentation of + the underlying [react/stream](https://github.com/reactphp/stream) component. + +* If you want to process compressed NDJSON files (`.ndjson.gz` file extension), + you may want to use [clue/reactphp-zlib](https://github.com/clue/reactphp-zlib) + on the compressed input stream before passing the decompressed stream to the NDJSON decoder. + +* If you want to create compressed NDJSON files (`.ndjson.gz` file extension), + you may want to use [clue/reactphp-zlib](https://github.com/clue/reactphp-zlib) + on the resulting NDJSON encoder output stream before passing the compressed + stream to the file output stream. + +* If you want to concurrently process the records from your NDJSON stream, + you may want to use [clue/reactphp-flux](https://github.com/clue/reactphp-flux) + to concurrently process many (but not too many) records at once. + +* If you want to process structured data in the more common text-based format, + you may want to use [clue/reactphp-csv](https://github.com/clue/reactphp-csv) + to process Comma-Separated-Values (CSV) files (`.csv` file extension). diff --git a/trilhas_poo/vendor/clue/ndjson-react/composer.json b/trilhas_poo/vendor/clue/ndjson-react/composer.json new file mode 100644 index 0000000..01a4b85 --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/composer.json @@ -0,0 +1,31 @@ +{ + "name": "clue/ndjson-react", + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "keywords": ["NDJSON", "newline", "JSON", "jsonlines", "streaming", "ReactPHP"], + "homepage": "https://github.com/clue/reactphp-ndjson", + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "require": { + "php": ">=5.3", + "react/stream": "^1.2" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react/event-loop": "^1.2" + }, + "autoload": { + "psr-4": { + "Clue\\React\\NDJson\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Clue\\Tests\\React\\NDJson\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/clue/ndjson-react/src/Decoder.php b/trilhas_poo/vendor/clue/ndjson-react/src/Decoder.php new file mode 100644 index 0000000..876ff2b --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/src/Decoder.php @@ -0,0 +1,166 @@ +input = $input; + + if (!$input->isReadable()) { + $this->close(); + return; + } + + $this->assoc = $assoc; + $this->depth = $depth; + $this->options = $options; + $this->maxlength = $maxlength; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->buffer = ''; + + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + /** @internal */ + public function handleData($data) + { + if (!\is_string($data)) { + $this->handleError(new \UnexpectedValueException('Expected stream to emit string, but got ' . \gettype($data))); + return; + } + + $this->buffer .= $data; + + // keep parsing while a newline has been found + while (($newline = \strpos($this->buffer, "\n")) !== false && $newline <= $this->maxlength) { + // read data up until newline and remove from buffer + $data = (string)\substr($this->buffer, 0, $newline); + $this->buffer = (string)\substr($this->buffer, $newline + 1); + + // decode data with options given in ctor + // @codeCoverageIgnoreStart + if ($this->options === 0) { + $data = \json_decode($data, $this->assoc, $this->depth); + } else { + assert(\PHP_VERSION_ID >= 50400); + $data = \json_decode($data, $this->assoc, $this->depth, $this->options); + } + // @codeCoverageIgnoreEnd + + // abort stream if decoding failed + if ($data === null && \json_last_error() !== \JSON_ERROR_NONE) { + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID > 50500) { + $errstr = \json_last_error_msg(); + } elseif (\json_last_error() === \JSON_ERROR_SYNTAX) { + $errstr = 'Syntax error'; + } else { + $errstr = 'Unknown error'; + } + // @codeCoverageIgnoreEnd + return $this->handleError(new \RuntimeException('Unable to decode JSON: ' . $errstr, \json_last_error())); + } + + $this->emit('data', array($data)); + } + + if (isset($this->buffer[$this->maxlength])) { + $this->handleError(new \OverflowException('Buffer size exceeded')); + } + } + + /** @internal */ + public function handleEnd() + { + if ($this->buffer !== '') { + $this->handleData("\n"); + } + + if (!$this->closed) { + $this->emit('end'); + $this->close(); + } + } + + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + $this->close(); + } +} diff --git a/trilhas_poo/vendor/clue/ndjson-react/src/Encoder.php b/trilhas_poo/vendor/clue/ndjson-react/src/Encoder.php new file mode 100644 index 0000000..30d5c31 --- /dev/null +++ b/trilhas_poo/vendor/clue/ndjson-react/src/Encoder.php @@ -0,0 +1,144 @@ +output = $output; + + if (!$output->isWritable()) { + $this->close(); + return; + } + + $this->options = $options; + $this->depth = $depth; + + $this->output->on('drain', array($this, 'handleDrain')); + $this->output->on('error', array($this, 'handleError')); + $this->output->on('close', array($this, 'close')); + } + + public function write($data) + { + if ($this->closed) { + return false; + } + + // we have to handle PHP warnings for legacy PHP < 5.5 + // certain values (such as INF etc.) emit a warning, but still encode successfully + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID < 50500) { + $errstr = null; + \set_error_handler(function ($_, $error) use (&$errstr) { + $errstr = $error; + }); + + // encode data with options given in ctor (depth not supported) + $data = \json_encode($data, $this->options); + + // always check error code and match missing error messages + \restore_error_handler(); + $errno = \json_last_error(); + if (\defined('JSON_ERROR_UTF8') && $errno === \JSON_ERROR_UTF8) { + // const JSON_ERROR_UTF8 added in PHP 5.3.3, but no error message assigned in legacy PHP < 5.5 + // this overrides PHP 5.3.14 only: https://3v4l.org/IGP8Z#v5314 + $errstr = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + } elseif ($errno !== \JSON_ERROR_NONE && $errstr === null) { + // error number present, but no error message applicable + $errstr = 'Unknown error'; + } + + // abort stream if encoding fails + if ($errno !== \JSON_ERROR_NONE || $errstr !== null) { + $this->handleError(new \RuntimeException('Unable to encode JSON: ' . $errstr, $errno)); + return false; + } + } else { + // encode data with options given in ctor + $data = \json_encode($data, $this->options, $this->depth); + + // abort stream if encoding fails + if ($data === false && \json_last_error() !== \JSON_ERROR_NONE) { + $this->handleError(new \RuntimeException('Unable to encode JSON: ' . \json_last_error_msg(), \json_last_error())); + return false; + } + } + // @codeCoverageIgnoreEnd + + return $this->output->write($data . "\n"); + } + + public function end($data = null) + { + if ($data !== null) { + $this->write($data); + } + + $this->output->end(); + } + + public function isWritable() + { + return !$this->closed; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->output->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleDrain() + { + $this->emit('drain'); + } + + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + $this->close(); + } +} diff --git a/trilhas_poo/vendor/composer/ClassLoader.php b/trilhas_poo/vendor/composer/ClassLoader.php new file mode 100644 index 0000000..7824d8f --- /dev/null +++ b/trilhas_poo/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/trilhas_poo/vendor/composer/InstalledVersions.php b/trilhas_poo/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..2052022 --- /dev/null +++ b/trilhas_poo/vendor/composer/InstalledVersions.php @@ -0,0 +1,396 @@ + + * 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 string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to + * @internal + */ + private static $selfDir = null; + + /** + * @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 + */ + private static $installedIsLocalDir; + + /** + * @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(); + + // when using reload, we disable the duplicate protection to ensure that self::$installed data is + // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not, + // so we have to assume it does not, and that may result in duplicate data being returned when listing + // all installed packages for example + self::$installedIsLocalDir = false; + } + + /** + * @return string + */ + private static function getSelfDir() + { + if (self::$selfDir === null) { + self::$selfDir = strtr(__DIR__, '\\', '/'); + } + + return self::$selfDir; + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + $copiedLocalDir = false; + + if (self::$canGetVendors) { + $selfDir = self::getSelfDir(); + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + $vendorDir = strtr($vendorDir, '\\', '/'); + 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'; + self::$installedByVendor[$vendorDir] = $required; + $installed[] = $required; + if (self::$installed === null && $vendorDir.'/composer' === $selfDir) { + self::$installed = $required; + self::$installedIsLocalDir = true; + } + } + if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) { + $copiedLocalDir = true; + } + } + } + + 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() && !$copiedLocalDir) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/trilhas_poo/vendor/composer/LICENSE b/trilhas_poo/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/trilhas_poo/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/trilhas_poo/vendor/composer/autoload_classmap.php b/trilhas_poo/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..fbdee41 --- /dev/null +++ b/trilhas_poo/vendor/composer/autoload_classmap.php @@ -0,0 +1,43 @@ + $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'DelayedTargetValidation' => $vendorDir . '/symfony/polyfill-php85/Resources/stubs/DelayedTargetValidation.php', + 'Deprecated' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Deprecated.php', + 'Filter\\FilterException' => $vendorDir . '/symfony/polyfill-php85/Resources/stubs/Filter/FilterException.php', + 'Filter\\FilterFailedException' => $vendorDir . '/symfony/polyfill-php85/Resources/stubs/Filter/FilterFailedException.php', + 'NoDiscard' => $vendorDir . '/symfony/polyfill-php85/Resources/stubs/NoDiscard.php', + 'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'Pdo\\Dblib' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Dblib.php', + 'Pdo\\Firebird' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Firebird.php', + 'Pdo\\Mysql' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Mysql.php', + 'Pdo\\Odbc' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Odbc.php', + 'Pdo\\Pgsql' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Pgsql.php', + 'Pdo\\Sqlite' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/Pdo/Sqlite.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReflectionConstant' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/ReflectionConstant.php', + 'ReturnTypeWillChange' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'RoundingMode' => $vendorDir . '/symfony/polyfill-php84/Resources/stubs/RoundingMode.php', + 'SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php', + 'SebastianBergmann\\Diff\\ConfigurationException' => $vendorDir . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php', + 'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php', + 'SebastianBergmann\\Diff\\Exception' => $vendorDir . '/sebastian/diff/src/Exception/Exception.php', + 'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php', + 'SebastianBergmann\\Diff\\MyersDiff' => $vendorDir . '/sebastian/diff/src/MyersDiff.php', + 'SebastianBergmann\\Diff\\NoMiddleSnakeFoundException' => $vendorDir . '/sebastian/diff/src/Exception/NoMiddleSnakeFoundException.php', + 'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', +); diff --git a/trilhas_poo/vendor/composer/autoload_files.php b/trilhas_poo/vendor/composer/autoload_files.php new file mode 100644 index 0000000..45aaa22 --- /dev/null +++ b/trilhas_poo/vendor/composer/autoload_files.php @@ -0,0 +1,20 @@ + $vendorDir . '/symfony/deprecation-contracts/function.php', + 'ad155f8f1cf0d418fe49e248db8c661b' => $vendorDir . '/react/promise/src/functions_include.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '606a39d89246991a373564698c2d8383' => $vendorDir . '/symfony/polyfill-php85/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php', + '9d2b9fc6db0f153a0a149fefb182415e' => $vendorDir . '/symfony/polyfill-php84/bootstrap.php', +); diff --git a/trilhas_poo/vendor/composer/autoload_namespaces.php b/trilhas_poo/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/trilhas_poo/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/symfony/polyfill-php85'), + 'Symfony\\Polyfill\\Php84\\' => array($vendorDir . '/symfony/polyfill-php84'), + 'Symfony\\Polyfill\\Php81\\' => array($vendorDir . '/symfony/polyfill-php81'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'), + 'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'), + 'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'), + 'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'), + 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'), + 'Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'), + 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), + 'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'), + 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), + 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'React\\Stream\\' => array($vendorDir . '/react/stream/src'), + 'React\\Socket\\' => array($vendorDir . '/react/socket/src'), + 'React\\Promise\\' => array($vendorDir . '/react/promise/src'), + 'React\\EventLoop\\' => array($vendorDir . '/react/event-loop/src'), + 'React\\Dns\\' => array($vendorDir . '/react/dns/src'), + 'React\\ChildProcess\\' => array($vendorDir . '/react/child-process/src'), + 'React\\Cache\\' => array($vendorDir . '/react/cache/src'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'PhpCsFixer\\' => array($vendorDir . '/friendsofphp/php-cs-fixer/src'), + 'Fidry\\CpuCoreCounter\\' => array($vendorDir . '/fidry/cpu-core-counter/src'), + 'Evenement\\' => array($vendorDir . '/evenement/evenement/src'), + 'Ergebnis\\AgentDetector\\' => array($vendorDir . '/ergebnis/agent-detector/src'), + 'Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'), + 'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'), + 'Composer\\Pcre\\' => array($vendorDir . '/composer/pcre/src'), + 'Clue\\React\\NDJson\\' => array($vendorDir . '/clue/ndjson-react/src'), + 'Ana\\TrilhasPoo\\' => array($baseDir . '/src'), +); diff --git a/trilhas_poo/vendor/composer/autoload_real.php b/trilhas_poo/vendor/composer/autoload_real.php new file mode 100644 index 0000000..ba51910 --- /dev/null +++ b/trilhas_poo/vendor/composer/autoload_real.php @@ -0,0 +1,48 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInit645796bb26c131e8fb0dbbf76b217216::$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/trilhas_poo/vendor/composer/autoload_static.php b/trilhas_poo/vendor/composer/autoload_static.php new file mode 100644 index 0000000..416be07 --- /dev/null +++ b/trilhas_poo/vendor/composer/autoload_static.php @@ -0,0 +1,281 @@ + __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + 'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + '8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php', + 'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php', + '606a39d89246991a373564698c2d8383' => __DIR__ . '/..' . '/symfony/polyfill-php85/bootstrap.php', + 'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '23c18046f52bef3eea034657bafda50f' => __DIR__ . '/..' . '/symfony/polyfill-php81/bootstrap.php', + '9d2b9fc6db0f153a0a149fefb182415e' => __DIR__ . '/..' . '/symfony/polyfill-php84/bootstrap.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symfony\\Polyfill\\Php85\\' => 23, + 'Symfony\\Polyfill\\Php84\\' => 23, + 'Symfony\\Polyfill\\Php81\\' => 23, + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => 33, + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => 31, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Contracts\\Service\\' => 26, + 'Symfony\\Contracts\\EventDispatcher\\' => 34, + 'Symfony\\Component\\String\\' => 25, + 'Symfony\\Component\\Stopwatch\\' => 28, + 'Symfony\\Component\\Process\\' => 26, + 'Symfony\\Component\\OptionsResolver\\' => 34, + 'Symfony\\Component\\Finder\\' => 25, + 'Symfony\\Component\\Filesystem\\' => 29, + 'Symfony\\Component\\EventDispatcher\\' => 34, + 'Symfony\\Component\\Console\\' => 26, + ), + 'R' => + array ( + 'React\\Stream\\' => 13, + 'React\\Socket\\' => 13, + 'React\\Promise\\' => 14, + 'React\\EventLoop\\' => 16, + 'React\\Dns\\' => 10, + 'React\\ChildProcess\\' => 19, + 'React\\Cache\\' => 12, + ), + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\EventDispatcher\\' => 20, + 'Psr\\Container\\' => 14, + 'PhpCsFixer\\' => 11, + ), + 'F' => + array ( + 'Fidry\\CpuCoreCounter\\' => 21, + ), + 'E' => + array ( + 'Evenement\\' => 10, + 'Ergebnis\\AgentDetector\\' => 23, + ), + 'C' => + array ( + 'Composer\\XdebugHandler\\' => 23, + 'Composer\\Semver\\' => 16, + 'Composer\\Pcre\\' => 14, + 'Clue\\React\\NDJson\\' => 18, + ), + 'A' => + array ( + 'Ana\\TrilhasPoo\\' => 15, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Symfony\\Polyfill\\Php85\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php85', + ), + 'Symfony\\Polyfill\\Php84\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php84', + ), + 'Symfony\\Polyfill\\Php81\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php81', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'Symfony\\Polyfill\\Intl\\Normalizer\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer', + ), + 'Symfony\\Polyfill\\Intl\\Grapheme\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Contracts\\Service\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/service-contracts', + ), + 'Symfony\\Contracts\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts', + ), + 'Symfony\\Component\\String\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/string', + ), + 'Symfony\\Component\\Stopwatch\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/stopwatch', + ), + 'Symfony\\Component\\Process\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/process', + ), + 'Symfony\\Component\\OptionsResolver\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/options-resolver', + ), + 'Symfony\\Component\\Finder\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/finder', + ), + 'Symfony\\Component\\Filesystem\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/filesystem', + ), + 'Symfony\\Component\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', + ), + 'Symfony\\Component\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/console', + ), + 'React\\Stream\\' => + array ( + 0 => __DIR__ . '/..' . '/react/stream/src', + ), + 'React\\Socket\\' => + array ( + 0 => __DIR__ . '/..' . '/react/socket/src', + ), + 'React\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/react/promise/src', + ), + 'React\\EventLoop\\' => + array ( + 0 => __DIR__ . '/..' . '/react/event-loop/src', + ), + 'React\\Dns\\' => + array ( + 0 => __DIR__ . '/..' . '/react/dns/src', + ), + 'React\\ChildProcess\\' => + array ( + 0 => __DIR__ . '/..' . '/react/child-process/src', + ), + 'React\\Cache\\' => + array ( + 0 => __DIR__ . '/..' . '/react/cache/src', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'Psr\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/event-dispatcher/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'PhpCsFixer\\' => + array ( + 0 => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src', + ), + 'Fidry\\CpuCoreCounter\\' => + array ( + 0 => __DIR__ . '/..' . '/fidry/cpu-core-counter/src', + ), + 'Evenement\\' => + array ( + 0 => __DIR__ . '/..' . '/evenement/evenement/src', + ), + 'Ergebnis\\AgentDetector\\' => + array ( + 0 => __DIR__ . '/..' . '/ergebnis/agent-detector/src', + ), + 'Composer\\XdebugHandler\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/xdebug-handler/src', + ), + 'Composer\\Semver\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/semver/src', + ), + 'Composer\\Pcre\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/pcre/src', + ), + 'Clue\\React\\NDJson\\' => + array ( + 0 => __DIR__ . '/..' . '/clue/ndjson-react/src', + ), + 'Ana\\TrilhasPoo\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + ), + ); + + public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'DelayedTargetValidation' => __DIR__ . '/..' . '/symfony/polyfill-php85/Resources/stubs/DelayedTargetValidation.php', + 'Deprecated' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Deprecated.php', + 'Filter\\FilterException' => __DIR__ . '/..' . '/symfony/polyfill-php85/Resources/stubs/Filter/FilterException.php', + 'Filter\\FilterFailedException' => __DIR__ . '/..' . '/symfony/polyfill-php85/Resources/stubs/Filter/FilterFailedException.php', + 'NoDiscard' => __DIR__ . '/..' . '/symfony/polyfill-php85/Resources/stubs/NoDiscard.php', + 'Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php', + 'Pdo\\Dblib' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Dblib.php', + 'Pdo\\Firebird' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Firebird.php', + 'Pdo\\Mysql' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Mysql.php', + 'Pdo\\Odbc' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Odbc.php', + 'Pdo\\Pgsql' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Pgsql.php', + 'Pdo\\Sqlite' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/Pdo/Sqlite.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReflectionConstant' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/ReflectionConstant.php', + 'ReturnTypeWillChange' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'RoundingMode' => __DIR__ . '/..' . '/symfony/polyfill-php84/Resources/stubs/RoundingMode.php', + 'SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php', + 'SebastianBergmann\\Diff\\ConfigurationException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php', + 'SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php', + 'SebastianBergmann\\Diff\\Exception' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/Exception.php', + 'SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php', + 'SebastianBergmann\\Diff\\MyersDiff' => __DIR__ . '/..' . '/sebastian/diff/src/MyersDiff.php', + 'SebastianBergmann\\Diff\\NoMiddleSnakeFoundException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/NoMiddleSnakeFoundException.php', + 'SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit645796bb26c131e8fb0dbbf76b217216::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit645796bb26c131e8fb0dbbf76b217216::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit645796bb26c131e8fb0dbbf76b217216::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/trilhas_poo/vendor/composer/installed.json b/trilhas_poo/vendor/composer/installed.json new file mode 100644 index 0000000..951eabf --- /dev/null +++ b/trilhas_poo/vendor/composer/installed.json @@ -0,0 +1,2996 @@ +{ + "packages": [ + { + "name": "clue/ndjson-react", + "version": "v1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/clue/reactphp-ndjson.git", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/reactphp-ndjson/zipball/392dc165fce93b5bb5c637b67e59619223c931b0", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/stream": "^1.2" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react/event-loop": "^1.2" + }, + "time": "2022-12-23T10:58:28+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Clue\\React\\NDJson\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "homepage": "https://github.com/clue/reactphp-ndjson", + "keywords": [ + "NDJSON", + "json", + "jsonlines", + "newline", + "reactphp", + "streaming" + ], + "support": { + "issues": "https://github.com/clue/reactphp-ndjson/issues", + "source": "https://github.com/clue/reactphp-ndjson/tree/v1.3.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../clue/ndjson-react" + }, + { + "name": "composer/pcre", + "version": "3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "d5a341b3fb61f3001970940afb1d332968a183ed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/d5a341b3fb61f3001970940afb1d332968a183ed", + "reference": "d5a341b3fb61f3001970940afb1d332968a183ed", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<2.2.2" + }, + "require-dev": { + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^9" + }, + "time": "2026-06-07T11:47:49+00:00", + "type": "library", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + }, + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.4.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "install-path": "./pcre" + }, + { + "name": "composer/semver", + "version": "3.4.4", + "version_normalized": "3.4.4.0", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "time": "2025-08-20T19:15:30+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.4.4" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "install-path": "./semver" + }, + { + "name": "composer/xdebug-handler", + "version": "3.0.5", + "version_normalized": "3.0.5.0", + "source": { + "type": "git", + "url": "https://github.com/composer/xdebug-handler.git", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/xdebug-handler/zipball/6c1925561632e83d60a44492e0b344cf48ab85ef", + "reference": "6c1925561632e83d60a44492e0b344cf48ab85ef", + "shasum": "" + }, + "require": { + "composer/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "phpunit/phpunit": "^8.5 || ^9.6 || ^10.5" + }, + "time": "2024-05-06T16:37:16+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/xdebug-handler/issues", + "source": "https://github.com/composer/xdebug-handler/tree/3.0.5" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "install-path": "./xdebug-handler" + }, + { + "name": "ergebnis/agent-detector", + "version": "1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/ergebnis/agent-detector.git", + "reference": "e211f17928c8b95a51e06040792d57f5462fb271" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ergebnis/agent-detector/zipball/e211f17928c8b95a51e06040792d57f5462fb271", + "reference": "e211f17928c8b95a51e06040792d57f5462fb271", + "shasum": "" + }, + "require": { + "php": "~7.4.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.51.0", + "ergebnis/license": "^2.7.0", + "ergebnis/php-cs-fixer-config": "^6.60.2", + "ergebnis/phpstan-rules": "^2.13.1", + "ergebnis/phpunit-slow-test-detector": "^2.24.0", + "ergebnis/rector-rules": "^1.18.1", + "fakerphp/faker": "^1.24.1", + "infection/infection": "^0.26.6", + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^2.1.54", + "phpstan/phpstan-deprecation-rules": "^2.0.4", + "phpstan/phpstan-phpunit": "^2.0.16", + "phpstan/phpstan-strict-rules": "^2.0.10", + "phpunit/phpunit": "^9.6.34", + "rector/rector": "^2.4.2" + }, + "time": "2026-05-07T08:19:07+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + }, + "composer-normalize": { + "indent-size": 2, + "indent-style": "space" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Ergebnis\\AgentDetector\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Andreas Möller", + "email": "am@localheinz.com", + "homepage": "https://localheinz.com" + } + ], + "description": "Provides a detector for detecting the presence of an agent.", + "homepage": "https://github.com/ergebnis/agent-detector", + "support": { + "issues": "https://github.com/ergebnis/agent-detector/issues", + "security": "https://github.com/ergebnis/agent-detector/blob/main/.github/SECURITY.md", + "source": "https://github.com/ergebnis/agent-detector" + }, + "install-path": "../ergebnis/agent-detector" + }, + { + "name": "evenement/evenement", + "version": "v3.0.2", + "version_normalized": "3.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/igorw/evenement.git", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/igorw/evenement/zipball/0a16b0d71ab13284339abb99d9d2bd813640efbc", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^9 || ^6" + }, + "time": "2023-08-08T05:53:35+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Evenement\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https://github.com/igorw/evenement/issues", + "source": "https://github.com/igorw/evenement/tree/v3.0.2" + }, + "install-path": "../evenement/evenement" + }, + { + "name": "fidry/cpu-core-counter", + "version": "1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/theofidry/cpu-core-counter.git", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry/makefile": "^0.2.0", + "fidry/php-cs-fixer-config": "^1.1.2", + "phpstan/extension-installer": "^1.2.0", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-deprecation-rules": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^8.5.31 || ^9.5.26", + "webmozarts/strict-phpunit": "^7.5" + }, + "time": "2025-08-14T07:29:31+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Fidry\\CpuCoreCounter\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Tiny utility to get the number of CPU cores.", + "keywords": [ + "CPU", + "core" + ], + "support": { + "issues": "https://github.com/theofidry/cpu-core-counter/issues", + "source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0" + }, + "funding": [ + { + "url": "https://github.com/theofidry", + "type": "github" + } + ], + "install-path": "../fidry/cpu-core-counter" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.95.15", + "version_normalized": "3.95.15.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "3e47e5d50046f87e3244acde2fe655d1a3b72555" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/3e47e5d50046f87e3244acde2fe655d1a3b72555", + "reference": "3e47e5d50046f87e3244acde2fe655d1a3b72555", + "shasum": "" + }, + "require": { + "clue/ndjson-react": "^1.3", + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.5", + "ergebnis/agent-detector": "^1.2", + "ext-filter": "*", + "ext-hash": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "fidry/cpu-core-counter": "^1.3", + "php": "^7.4 || ^8.0", + "react/child-process": "^0.6.6", + "react/event-loop": "^1.5", + "react/socket": "^1.16", + "react/stream": "^1.4", + "sebastian/diff": "^4.0.6 || ^5.1.1 || ^6.0.2 || ^7.0 || ^8.0 || ^9.0", + "symfony/console": "^5.4.47 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/event-dispatcher": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/filesystem": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/finder": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/options-resolver": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/polyfill-mbstring": "^1.37", + "symfony/polyfill-php80": "^1.37", + "symfony/polyfill-php81": "^1.37", + "symfony/polyfill-php84": "^1.37", + "symfony/process": "^5.4.47 || ^6.4.24 || ^7.2 || ^8.0", + "symfony/stopwatch": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3.1 || ^2.11.0", + "infection/infection": "^0.32.7", + "justinrainbow/json-schema": "^6.10.0", + "keradus/cli-executor": "^2.3", + "mikey179/vfsstream": "^1.6.12", + "php-coveralls/php-coveralls": "^2.9.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.8", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.8", + "phpunit/phpunit": "^9.6.35 || ^10.5.64 || ^11.5.56 || ^12.5.31", + "symfony/polyfill-php85": "^1.38", + "symfony/var-dumper": "^5.4.48 || ^6.4.36 || ^7.4.8 || ^8.1.0", + "symfony/yaml": "^5.4.53 || ^6.4.41 || ^7.4.13 || ^8.1.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "time": "2026-07-15T09:51:47+00:00", + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + }, + "exclude-from-classmap": [ + "src/**/Internal/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.15" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "install-path": "../friendsofphp/php-cs-fixer" + }, + { + "name": "psr/container", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:47:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https://github.com/php-fig/container/issues", + "source": "https://github.com/php-fig/container/tree/2.0.2" + }, + "install-path": "../psr/container" + }, + { + "name": "psr/event-dispatcher", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", + "shasum": "" + }, + "require": { + "php": ">=7.2.0" + }, + "time": "2019-01-08T18:20:26+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Standard interfaces for event handling.", + "keywords": [ + "events", + "psr", + "psr-14" + ], + "support": { + "issues": "https://github.com/php-fig/event-dispatcher/issues", + "source": "https://github.com/php-fig/event-dispatcher/tree/1.0.0" + }, + "install-path": "../psr/event-dispatcher" + }, + { + "name": "psr/log", + "version": "3.0.2", + "version_normalized": "3.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2024-09-11T13:17:53+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "install-path": "../psr/log" + }, + { + "name": "react/cache", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/cache.git", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/cache/zipball/d47c472b64aa5608225f47965a484b75c7817d5b", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "time": "2022-11-30T15:59:55+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/cache/issues", + "source": "https://github.com/reactphp/cache/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/cache" + }, + { + "name": "react/child-process", + "version": "v0.6.7", + "version_normalized": "0.6.7.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/child-process.git", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/child-process/zipball/970f0e71945556422ee4570ccbabaedc3cf04ad3", + "reference": "970f0e71945556422ee4570ccbabaedc3cf04ad3", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/event-loop": "^1.2", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/socket": "^1.16", + "sebastian/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "time": "2025-12-23T15:25:20+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\ChildProcess\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": [ + "event-driven", + "process", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/child-process/issues", + "source": "https://github.com/reactphp/child-process/tree/v0.6.7" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/child-process" + }, + { + "name": "react/dns", + "version": "v1.14.0", + "version_normalized": "1.14.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/dns.git", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/dns/zipball/7562c05391f42701c1fccf189c8225fece1cd7c3", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3 || ^2", + "react/promise-timer": "^1.11" + }, + "time": "2025-11-18T19:34:28+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Dns\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/dns/issues", + "source": "https://github.com/reactphp/dns/tree/v1.14.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/dns" + }, + { + "name": "react/event-loop", + "version": "v1.6.0", + "version_normalized": "1.6.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/event-loop.git", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/event-loop/zipball/ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "time": "2025-11-17T20:46:25+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https://github.com/reactphp/event-loop/issues", + "source": "https://github.com/reactphp/event-loop/tree/v1.6.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/event-loop" + }, + { + "name": "react/promise", + "version": "v3.3.0", + "version_normalized": "3.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise.git", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise/zipball/23444f53a813a3296c1368bb104793ce8d88f04a", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a", + "shasum": "" + }, + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan/phpstan": "1.12.28 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^7.5" + }, + "time": "2025-08-19T18:57:03+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "React\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https://github.com/reactphp/promise/issues", + "source": "https://github.com/reactphp/promise/tree/v3.3.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/promise" + }, + { + "name": "react/socket", + "version": "v1.17.0", + "version_normalized": "1.17.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/socket.git", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/socket/zipball/ef5b17b81f6f60504c539313f94f2d826c5faa08", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/dns": "^1.13", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.6 || ^1.2.1", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3.3 || ^2", + "react/promise-stream": "^1.4", + "react/promise-timer": "^1.11" + }, + "time": "2025-11-19T20:47:34+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Socket\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https://github.com/reactphp/socket/issues", + "source": "https://github.com/reactphp/socket/tree/v1.17.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/socket" + }, + { + "name": "react/stream", + "version": "v1.4.0", + "version_normalized": "1.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/stream.git", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/stream/zipball/1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react/event-loop": "^1.2" + }, + "require-dev": { + "clue/stream-filter": "~1.2", + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "time": "2024-06-11T12:45:25+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Stream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https://github.com/reactphp/stream/issues", + "source": "https://github.com/reactphp/stream/tree/v1.4.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "install-path": "../react/stream" + }, + { + "name": "sebastian/diff", + "version": "9.0.0", + "version_normalized": "9.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/a3fb6a298a265ff487a91bbea46e03cd01dbb226", + "reference": "a3fb6a298a265ff487a91bbea46e03cd01dbb226", + "shasum": "" + }, + "require": { + "php": ">=8.4" + }, + "require-dev": { + "phpunit/phpunit": "^13.2", + "symfony/process": "^7.4.13" + }, + "time": "2026-06-05T03:04:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "9.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/9.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/diff", + "type": "tidelift" + } + ], + "install-path": "../sebastian/diff" + }, + { + "name": "symfony/console", + "version": "v8.1.1", + "version_normalized": "8.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d", + "reference": "b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-mbstring": "^1.0", + "symfony/polyfill-php85": "^1.32", + "symfony/service-contracts": "^2.5|^3", + "symfony/string": "^7.4.6|^8.0.6" + }, + "conflict": { + "symfony/dependency-injection": "<8.1", + "symfony/event-dispatcher": "<8.1" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^7.4|^8.0", + "symfony/dependency-injection": "^8.1", + "symfony/event-dispatcher": "^8.1", + "symfony/filesystem": "^7.4|^8.0", + "symfony/http-foundation": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/lock": "^7.4|^8.0", + "symfony/messenger": "^7.4|^8.0", + "symfony/mime": "^7.4|^8.0", + "symfony/process": "^7.4|^8.0", + "symfony/stopwatch": "^7.4|^8.0", + "symfony/uid": "^7.4|^8.0", + "symfony/validator": "^7.4|^8.0", + "symfony/var-dumper": "^7.4|^8.0" + }, + "time": "2026-06-16T12:55:20+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https://symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https://github.com/symfony/console/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/console" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.7.1", + "version_normalized": "3.7.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2026-06-05T06:23:12+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "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.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/event-dispatcher", + "version": "v8.1.1", + "version_normalized": "8.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "abd6c11dc468725d1627302ad10f6cd486e9e3d0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/abd6c11dc468725d1627302ad10f6cd486e9e3d0", + "reference": "abd6c11dc468725d1627302ad10f6cd486e9e3d0", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/event-dispatcher-contracts": "^2.5|^3" + }, + "conflict": { + "symfony/security-http": "<7.4", + "symfony/service-contracts": "<2.5" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^7.4|^8.0", + "symfony/dependency-injection": "^7.4|^8.0", + "symfony/error-handler": "^7.4|^8.0", + "symfony/expression-language": "^7.4|^8.0", + "symfony/framework-bundle": "^7.4|^8.0", + "symfony/http-foundation": "^7.4|^8.0", + "symfony/service-contracts": "^2.5|^3", + "symfony/stopwatch": "^7.4|^8.0" + }, + "time": "2026-06-09T12:28:30+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/event-dispatcher/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v3.7.1", + "version_normalized": "3.7.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/event-dispatcher": "^1" + }, + "time": "2026-06-05T06:23:12+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/event-dispatcher-contracts" + }, + { + "name": "symfony/filesystem", + "version": "v8.1.0", + "version_normalized": "8.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/99aec13b82b4967ec5088222c4a3ecca955949c2", + "reference": "99aec13b82b4967ec5088222c4a3ecca955949c2", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3", + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-mbstring": "~1.8" + }, + "require-dev": { + "symfony/process": "^7.4|^8.0" + }, + "time": "2026-05-29T05:06:50+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/filesystem/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/filesystem" + }, + { + "name": "symfony/finder", + "version": "v8.1.1", + "version_normalized": "8.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/e2989e762c70f9490fa3a00a0ac0fae5aa97a531", + "reference": "e2989e762c70f9490fa3a00a0ac0fae5aa97a531", + "shasum": "" + }, + "require": { + "php": ">=8.4.1" + }, + "require-dev": { + "symfony/filesystem": "^7.4|^8.0" + }, + "time": "2026-06-27T09:05:56+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/finder/tree/v8.1.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/finder" + }, + { + "name": "symfony/options-resolver", + "version": "v8.1.0", + "version_normalized": "8.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "88f9c561f678a02d54b897014049fa839e33ff82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/88f9c561f678a02d54b897014049fa839e33ff82", + "reference": "88f9c561f678a02d54b897014049fa839e33ff82", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "time": "2026-05-29T05:06:50+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https://github.com/symfony/options-resolver/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/options-resolver" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.37.0", + "version_normalized": "1.37.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/141046a8f9477948ff284fa65be2095baafb94f2", + "reference": "141046a8f9477948ff284fa65be2095baafb94f2", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2026-04-10T16:19:22+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-intl-grapheme", + "version": "v1.38.1", + "version_normalized": "1.38.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-grapheme.git", + "reference": "e9247d281d694a5120554d9afaf54e070e88a603" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/e9247d281d694a5120554d9afaf54e070e88a603", + "reference": "e9247d281d694a5120554d9afaf54e070e88a603", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2026-05-26T05:58:03+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Grapheme\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's grapheme_* functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "grapheme", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-grapheme" + }, + { + "name": "symfony/polyfill-intl-normalizer", + "version": "v1.38.0", + "version_normalized": "1.38.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-normalizer.git", + "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/2d446c214bdbe5b71bde5011b060a05fece3ae6b", + "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance" + }, + "time": "2026-05-25T13:48:31+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Normalizer\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's Normalizer class and related functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "intl", + "normalizer", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.38.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-intl-normalizer" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.38.2", + "version_normalized": "1.38.2.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", + "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": ">=7.2" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2026-05-27T06:59:30+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.38.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-mbstring" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.37.0", + "version_normalized": "1.37.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-04-10T16:19:22+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.38.1", + "version_normalized": "1.38.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "6bfb9c766cacffbc8e118cb87217d08ed84e5cd7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/6bfb9c766cacffbc8e118cb87217d08ed84e5cd7", + "reference": "6bfb9c766cacffbc8e118cb87217d08ed84e5cd7", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-05-26T12:45:58+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php81" + }, + { + "name": "symfony/polyfill-php84", + "version": "v1.38.1", + "version_normalized": "1.38.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php84.git", + "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php84/zipball/f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa", + "reference": "f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-05-26T12:51:13+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php84\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.4+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php84/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php84" + }, + { + "name": "symfony/polyfill-php85", + "version": "v1.38.1", + "version_normalized": "1.38.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php85.git", + "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1", + "reference": "ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "time": "2026-05-26T02:25:22+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php85\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.5+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php85/tree/v1.38.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php85" + }, + { + "name": "symfony/process", + "version": "v8.1.0", + "version_normalized": "8.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/c4a9e58f235a6bf7f97ffbfedae2687353ac79e5", + "reference": "c4a9e58f235a6bf7f97ffbfedae2687353ac79e5", + "shasum": "" + }, + "require": { + "php": ">=8.4.1" + }, + "time": "2026-05-29T05:06:50+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Executes commands in sub-processes", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/process/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/process" + }, + { + "name": "symfony/service-contracts", + "version": "v3.7.1", + "version_normalized": "3.7.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/service-contracts.git", + "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/c0a284bab1ed8aa0417e3d69250ab437739563a0", + "reference": "c0a284bab1ed8aa0417e3d69250ab437739563a0", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr/container": "^1.1|^2.0", + "symfony/deprecation-contracts": "^2.5|^3" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "time": "2026-06-16T09:55:08+00:00", + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/service-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/service-contracts" + }, + { + "name": "symfony/stopwatch", + "version": "v8.1.0", + "version_normalized": "8.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "21c07b026905d596e8379caeb115d87aa479499d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/21c07b026905d596e8379caeb115d87aa479499d", + "reference": "21c07b026905d596e8379caeb115d87aa479499d", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/service-contracts": "^2.5|^3" + }, + "time": "2026-05-29T05:06:50+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/stopwatch" + }, + { + "name": "symfony/string", + "version": "v8.1.0", + "version_normalized": "8.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/string.git", + "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/string/zipball/afd5944f4005862d961efb85c8bbd5c523c4e3c9", + "reference": "afd5944f4005862d961efb85c8bbd5c523c4e3c9", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-intl-grapheme": "^1.33", + "symfony/polyfill-intl-normalizer": "^1.0", + "symfony/polyfill-mbstring": "^1.0" + }, + "conflict": { + "symfony/translation-contracts": "<2.5" + }, + "require-dev": { + "symfony/emoji": "^7.4|^8.0", + "symfony/http-client": "^7.4|^8.0", + "symfony/intl": "^7.4|^8.0", + "symfony/translation-contracts": "^2.5|^3.0", + "symfony/var-exporter": "^7.4|^8.0" + }, + "time": "2026-05-29T05:06:50+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "Resources/functions.php" + ], + "psr-4": { + "Symfony\\Component\\String\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way", + "homepage": "https://symfony.com", + "keywords": [ + "grapheme", + "i18n", + "string", + "unicode", + "utf-8", + "utf8" + ], + "support": { + "source": "https://github.com/symfony/string/tree/v8.1.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/string" + } + ], + "dev": true, + "dev-package-names": [ + "clue/ndjson-react", + "composer/pcre", + "composer/semver", + "composer/xdebug-handler", + "ergebnis/agent-detector", + "evenement/evenement", + "fidry/cpu-core-counter", + "friendsofphp/php-cs-fixer", + "psr/container", + "psr/event-dispatcher", + "psr/log", + "react/cache", + "react/child-process", + "react/dns", + "react/event-loop", + "react/promise", + "react/socket", + "react/stream", + "sebastian/diff", + "symfony/console", + "symfony/deprecation-contracts", + "symfony/event-dispatcher", + "symfony/event-dispatcher-contracts", + "symfony/filesystem", + "symfony/finder", + "symfony/options-resolver", + "symfony/polyfill-ctype", + "symfony/polyfill-intl-grapheme", + "symfony/polyfill-intl-normalizer", + "symfony/polyfill-mbstring", + "symfony/polyfill-php80", + "symfony/polyfill-php81", + "symfony/polyfill-php84", + "symfony/polyfill-php85", + "symfony/process", + "symfony/service-contracts", + "symfony/stopwatch", + "symfony/string" + ] +} diff --git a/trilhas_poo/vendor/composer/installed.php b/trilhas_poo/vendor/composer/installed.php new file mode 100644 index 0000000..9eeff9a --- /dev/null +++ b/trilhas_poo/vendor/composer/installed.php @@ -0,0 +1,383 @@ + array( + 'name' => 'ana/trilhas_poo', + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '9a337db81664cdf98fb2b0d2db6fa318563c871f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'ana/trilhas_poo' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'reference' => '9a337db81664cdf98fb2b0d2db6fa318563c871f', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'clue/ndjson-react' => array( + 'pretty_version' => 'v1.3.0', + 'version' => '1.3.0.0', + 'reference' => '392dc165fce93b5bb5c637b67e59619223c931b0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../clue/ndjson-react', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'composer/pcre' => array( + 'pretty_version' => '3.4.0', + 'version' => '3.4.0.0', + 'reference' => 'd5a341b3fb61f3001970940afb1d332968a183ed', + 'type' => 'library', + 'install_path' => __DIR__ . '/./pcre', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'composer/semver' => array( + 'pretty_version' => '3.4.4', + 'version' => '3.4.4.0', + 'reference' => '198166618906cb2de69b95d7d47e5fa8aa1b2b95', + 'type' => 'library', + 'install_path' => __DIR__ . '/./semver', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'composer/xdebug-handler' => array( + 'pretty_version' => '3.0.5', + 'version' => '3.0.5.0', + 'reference' => '6c1925561632e83d60a44492e0b344cf48ab85ef', + 'type' => 'library', + 'install_path' => __DIR__ . '/./xdebug-handler', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'ergebnis/agent-detector' => array( + 'pretty_version' => '1.2.0', + 'version' => '1.2.0.0', + 'reference' => 'e211f17928c8b95a51e06040792d57f5462fb271', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ergebnis/agent-detector', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'evenement/evenement' => array( + 'pretty_version' => 'v3.0.2', + 'version' => '3.0.2.0', + 'reference' => '0a16b0d71ab13284339abb99d9d2bd813640efbc', + 'type' => 'library', + 'install_path' => __DIR__ . '/../evenement/evenement', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'fidry/cpu-core-counter' => array( + 'pretty_version' => '1.3.0', + 'version' => '1.3.0.0', + 'reference' => 'db9508f7b1474469d9d3c53b86f817e344732678', + 'type' => 'library', + 'install_path' => __DIR__ . '/../fidry/cpu-core-counter', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'friendsofphp/php-cs-fixer' => array( + 'pretty_version' => 'v3.95.15', + 'version' => '3.95.15.0', + 'reference' => '3e47e5d50046f87e3244acde2fe655d1a3b72555', + 'type' => 'application', + 'install_path' => __DIR__ . '/../friendsofphp/php-cs-fixer', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'psr/container' => array( + 'pretty_version' => '2.0.2', + 'version' => '2.0.2.0', + 'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/container', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'psr/event-dispatcher' => array( + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/event-dispatcher', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'psr/event-dispatcher-implementation' => array( + 'dev_requirement' => true, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/log' => array( + 'pretty_version' => '3.0.2', + 'version' => '3.0.2.0', + 'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/log', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'psr/log-implementation' => array( + 'dev_requirement' => true, + 'provided' => array( + 0 => '1.0|2.0|3.0', + ), + ), + 'react/cache' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'reference' => 'd47c472b64aa5608225f47965a484b75c7817d5b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/cache', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/child-process' => array( + 'pretty_version' => 'v0.6.7', + 'version' => '0.6.7.0', + 'reference' => '970f0e71945556422ee4570ccbabaedc3cf04ad3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/child-process', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/dns' => array( + 'pretty_version' => 'v1.14.0', + 'version' => '1.14.0.0', + 'reference' => '7562c05391f42701c1fccf189c8225fece1cd7c3', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/dns', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/event-loop' => array( + 'pretty_version' => 'v1.6.0', + 'version' => '1.6.0.0', + 'reference' => 'ba276bda6083df7e0050fd9b33f66ad7a4ac747a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/event-loop', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/promise' => array( + 'pretty_version' => 'v3.3.0', + 'version' => '3.3.0.0', + 'reference' => '23444f53a813a3296c1368bb104793ce8d88f04a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/promise', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/socket' => array( + 'pretty_version' => 'v1.17.0', + 'version' => '1.17.0.0', + 'reference' => 'ef5b17b81f6f60504c539313f94f2d826c5faa08', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/socket', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'react/stream' => array( + 'pretty_version' => 'v1.4.0', + 'version' => '1.4.0.0', + 'reference' => '1e5b0acb8fe55143b5b426817155190eb6f5b18d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/stream', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'sebastian/diff' => array( + 'pretty_version' => '9.0.0', + 'version' => '9.0.0.0', + 'reference' => 'a3fb6a298a265ff487a91bbea46e03cd01dbb226', + 'type' => 'library', + 'install_path' => __DIR__ . '/../sebastian/diff', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/console' => array( + 'pretty_version' => 'v8.1.1', + 'version' => '8.1.1.0', + 'reference' => 'b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/console', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v3.7.1', + 'version' => '3.7.1.0', + 'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/event-dispatcher' => array( + 'pretty_version' => 'v8.1.1', + 'version' => '8.1.1.0', + 'reference' => 'abd6c11dc468725d1627302ad10f6cd486e9e3d0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/event-dispatcher-contracts' => array( + 'pretty_version' => 'v3.7.1', + 'version' => '3.7.1.0', + 'reference' => 'c7de7a00ffb67842132da02ea92988a39ccd9f4e', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/event-dispatcher-contracts', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/event-dispatcher-implementation' => array( + 'dev_requirement' => true, + 'provided' => array( + 0 => '2.0|3.0', + ), + ), + 'symfony/filesystem' => array( + 'pretty_version' => 'v8.1.0', + 'version' => '8.1.0.0', + 'reference' => '99aec13b82b4967ec5088222c4a3ecca955949c2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/filesystem', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/finder' => array( + 'pretty_version' => 'v8.1.1', + 'version' => '8.1.1.0', + 'reference' => 'e2989e762c70f9490fa3a00a0ac0fae5aa97a531', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/finder', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/options-resolver' => array( + 'pretty_version' => 'v8.1.0', + 'version' => '8.1.0.0', + 'reference' => '88f9c561f678a02d54b897014049fa839e33ff82', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/options-resolver', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-ctype' => array( + 'pretty_version' => 'v1.37.0', + 'version' => '1.37.0.0', + 'reference' => '141046a8f9477948ff284fa65be2095baafb94f2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-intl-grapheme' => array( + 'pretty_version' => 'v1.38.1', + 'version' => '1.38.1.0', + 'reference' => 'e9247d281d694a5120554d9afaf54e070e88a603', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-grapheme', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-intl-normalizer' => array( + 'pretty_version' => 'v1.38.0', + 'version' => '1.38.0.0', + 'reference' => '2d446c214bdbe5b71bde5011b060a05fece3ae6b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-intl-normalizer', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-mbstring' => array( + 'pretty_version' => 'v1.38.2', + 'version' => '1.38.2.0', + 'reference' => 'd3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.37.0', + 'version' => '1.37.0.0', + 'reference' => 'dfb55726c3a76ea3b6459fcfda1ec2d80a682411', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-php81' => array( + 'pretty_version' => 'v1.38.1', + 'version' => '1.38.1.0', + 'reference' => '6bfb9c766cacffbc8e118cb87217d08ed84e5cd7', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php81', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-php84' => array( + 'pretty_version' => 'v1.38.1', + 'version' => '1.38.1.0', + 'reference' => 'f4e1dfaee5b74aba5964fe1fd4dfc7ba5e3085fa', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php84', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/polyfill-php85' => array( + 'pretty_version' => 'v1.38.1', + 'version' => '1.38.1.0', + 'reference' => 'ba2ba04f3352cfa2dcbbcb90aee13ed967f505b1', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php85', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/process' => array( + 'pretty_version' => 'v8.1.0', + 'version' => '8.1.0.0', + 'reference' => 'c4a9e58f235a6bf7f97ffbfedae2687353ac79e5', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/process', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/service-contracts' => array( + 'pretty_version' => 'v3.7.1', + 'version' => '3.7.1.0', + 'reference' => 'c0a284bab1ed8aa0417e3d69250ab437739563a0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/service-contracts', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/stopwatch' => array( + 'pretty_version' => 'v8.1.0', + 'version' => '8.1.0.0', + 'reference' => '21c07b026905d596e8379caeb115d87aa479499d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/stopwatch', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/string' => array( + 'pretty_version' => 'v8.1.0', + 'version' => '8.1.0.0', + 'reference' => 'afd5944f4005862d961efb85c8bbd5c523c4e3c9', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/string', + 'aliases' => array(), + 'dev_requirement' => true, + ), + ), +); diff --git a/trilhas_poo/vendor/composer/pcre/LICENSE b/trilhas_poo/vendor/composer/pcre/LICENSE new file mode 100644 index 0000000..c5a282f --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2021 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/trilhas_poo/vendor/composer/pcre/README.md b/trilhas_poo/vendor/composer/pcre/README.md new file mode 100644 index 0000000..4906514 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/README.md @@ -0,0 +1,189 @@ +composer/pcre +============= + +PCRE wrapping library that offers type-safe `preg_*` replacements. + +This library gives you a way to ensure `preg_*` functions do not fail silently, returning +unexpected `null`s that may not be handled. + +As of 3.0 this library enforces [`PREG_UNMATCHED_AS_NULL`](#preg_unmatched_as_null) usage +for all matching and replaceCallback functions, [read more below](#preg_unmatched_as_null) +to understand the implications. + +It thus makes it easier to work with static analysis tools like PHPStan or Psalm as it +simplifies and reduces the possible return values from all the `preg_*` functions which +are quite packed with edge cases. As of v2.2.0 / v3.2.0 the library also comes with a +[PHPStan extension](#phpstan-extension) for parsing regular expressions and giving you even better output types. + +This library is a thin wrapper around `preg_*` functions with [some limitations](#restrictions--limitations). +If you are looking for a richer API to handle regular expressions have a look at +[rawr/t-regx](https://packagist.org/packages/rawr/t-regx) instead. + +[![Continuous Integration](https://github.com/composer/pcre/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/pcre/actions) + + +Installation +------------ + +Install the latest version with: + +```bash +$ composer require composer/pcre +``` + + +Requirements +------------ + +* PHP 7.4.0 is required for 3.x versions +* PHP 7.2.0 is required for 2.x versions +* PHP 5.3.2 is required for 1.x versions + + +Basic usage +----------- + +Instead of: + +```php +if (preg_match('{fo+}', $string, $matches)) { ... } +if (preg_match('{fo+}', $string, $matches, PREG_OFFSET_CAPTURE)) { ... } +if (preg_match_all('{fo+}', $string, $matches)) { ... } +$newString = preg_replace('{fo+}', 'bar', $string); +$newString = preg_replace_callback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = preg_replace_callback_array(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = preg_grep('{[a-z]}', $elements); +$array = preg_split('{[a-z]+}', $string); +``` + +You can now call these on the `Preg` class: + +```php +use Composer\Pcre\Preg; + +if (Preg::match('{fo+}', $string, $matches)) { ... } +if (Preg::matchWithOffsets('{fo+}', $string, $matches)) { ... } +if (Preg::matchAll('{fo+}', $string, $matches)) { ... } +$newString = Preg::replace('{fo+}', 'bar', $string); +$newString = Preg::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = Preg::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = Preg::grep('{[a-z]}', $elements); +$array = Preg::split('{[a-z]+}', $string); +``` + +The main difference is if anything fails to match/replace/.., it will throw a `Composer\Pcre\PcreException` +instead of returning `null` (or false in some cases), so you can now use the return values safely relying on +the fact that they can only be strings (for replace), ints (for match) or arrays (for grep/split). + +Additionally the `Preg` class provides match methods that return `bool` rather than `int`, for stricter type safety +when the number of pattern matches is not useful: + +```php +use Composer\Pcre\Preg; + +if (Preg::isMatch('{fo+}', $string, $matches)) // bool +if (Preg::isMatchAll('{fo+}', $string, $matches)) // bool +``` + +Finally the `Preg` class provides a few `*StrictGroups` method variants that ensure match groups +are always present and thus non-nullable, making it easier to write type-safe code: + +```php +use Composer\Pcre\Preg; + +// $matches is guaranteed to be an array of strings, if a subpattern does not match and produces a null it will throw +if (Preg::matchStrictGroups('{fo+}', $string, $matches)) +if (Preg::matchAllStrictGroups('{fo+}', $string, $matches)) +``` + +**Note:** This is generally safe to use as long as you do not have optional subpatterns (i.e. `(something)?` +or `(something)*` or branches with a `|` that result in some groups not being matched at all). +A subpattern that can match an empty string like `(.*)` is **not** optional, it will be present as an +empty string in the matches. A non-matching subpattern, even if optional like `(?:foo)?` will anyway not be present in +matches so it is also not a problem to use these with `*StrictGroups` methods. + +If you would prefer a slightly more verbose usage, replacing by-ref arguments by result objects, you can use the `Regex` class: + +```php +use Composer\Pcre\Regex; + +// this is useful when you are just interested in knowing if something matched +// as it returns a bool instead of int(1/0) for match +$bool = Regex::isMatch('{fo+}', $string); + +$result = Regex::match('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchWithOffsets('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchAll('{fo+}', $string); +if ($result->matched && $result->count > 3) { something($result->matches); } + +$newString = Regex::replace('{fo+}', 'bar', $string)->result; +$newString = Regex::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string)->result; +$newString = Regex::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string)->result; +``` + +Note that `preg_grep` and `preg_split` are only callable via the `Preg` class as they do not have +complex return types warranting a specific result object. + +See the [MatchResult](src/MatchResult.php), [MatchWithOffsetsResult](src/MatchWithOffsetsResult.php), [MatchAllResult](src/MatchAllResult.php), +[MatchAllWithOffsetsResult](src/MatchAllWithOffsetsResult.php), and [ReplaceResult](src/ReplaceResult.php) class sources for more details. + +Restrictions / Limitations +-------------------------- + +Due to type safety requirements a few restrictions are in place. + +- matching using `PREG_OFFSET_CAPTURE` is made available via `matchWithOffsets` and `matchAllWithOffsets`. + You cannot pass the flag to `match`/`matchAll`. +- `Preg::split` will also reject `PREG_SPLIT_OFFSET_CAPTURE` and you should use `splitWithOffsets` + instead. +- `matchAll` rejects `PREG_SET_ORDER` as it also changes the shape of the returned matches. There + is no alternative provided as you can fairly easily code around it. +- `preg_filter` is not supported as it has a rather crazy API, most likely you should rather + use `Preg::grep` in combination with some loop and `Preg::replace`. +- `replace`, `replaceCallback` and `replaceCallbackArray` do not support an array `$subject`, + only simple strings. +- As of 2.0, the library always uses `PREG_UNMATCHED_AS_NULL` for matching, which offers [much + saner/more predictable results](#preg_unmatched_as_null). As of 3.0 the flag is also set for + `replaceCallback` and `replaceCallbackArray`. + +#### PREG_UNMATCHED_AS_NULL + +As of 2.0, this library always uses PREG_UNMATCHED_AS_NULL for all `match*` and `isMatch*` +functions. As of 3.0 it is also done for `replaceCallback` and `replaceCallbackArray`. + +This means your matches will always contain all matching groups, either as null if unmatched +or as string if it matched. + +The advantages in clarity and predictability are clearer if you compare the two outputs of +running this with and without PREG_UNMATCHED_AS_NULL in $flags: + +```php +preg_match('/(a)(b)*(c)(d)*/', 'ac', $matches, $flags); +``` + +| no flag | PREG_UNMATCHED_AS_NULL | +| --- | --- | +| array (size=4) | array (size=5) | +| 0 => string 'ac' (length=2) | 0 => string 'ac' (length=2) | +| 1 => string 'a' (length=1) | 1 => string 'a' (length=1) | +| 2 => string '' (length=0) | 2 => null | +| 3 => string 'c' (length=1) | 3 => string 'c' (length=1) | +| | 4 => null | +| group 2 (any unmatched group preceding one that matched) is set to `''`. You cannot tell if it matched an empty string or did not match at all | group 2 is `null` when unmatched and a string if it matched, easy to check for | +| group 4 (any optional group without a matching one following) is missing altogether. So you have to check with `isset()`, but really you want `isset($m[4]) && $m[4] !== ''` for safety unless you are very careful to check that a non-optional group follows it | group 4 is always set, and null in this case as there was no match, easy to check for with `$m[4] !== null` | + +PHPStan Extension +----------------- + +To use the PHPStan extension if you do not use `phpstan/extension-installer` you can include `vendor/composer/pcre/extension.neon` in your PHPStan config. + +The extension provides much better type information for $matches as well as regex validation where possible. + +License +------- + +composer/pcre is licensed under the MIT License, see the LICENSE file for details. diff --git a/trilhas_poo/vendor/composer/pcre/composer.json b/trilhas_poo/vendor/composer/pcre/composer.json new file mode 100644 index 0000000..a6e72c3 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/composer.json @@ -0,0 +1,58 @@ +{ + "name": "composer/pcre", + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "type": "library", + "license": "MIT", + "keywords": [ + "pcre", + "regex", + "preg", + "regular expression" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9", + "phpstan/phpstan": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpstan/phpstan-deprecation-rules": "^2" + }, + "conflict": { + "phpstan/phpstan": "<2.2.2" + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\Pcre\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + }, + "phpstan": { + "includes": [ + "extension.neon" + ] + } + }, + "scripts": { + "test": [ + "@php vendor/bin/phpunit", + "@php vendor/bin/phpunit --testsuite phpstan" + ], + "phpstan": "@php phpstan analyse" + } +} diff --git a/trilhas_poo/vendor/composer/pcre/extension.neon b/trilhas_poo/vendor/composer/pcre/extension.neon new file mode 100644 index 0000000..b9cea11 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/extension.neon @@ -0,0 +1,22 @@ +# composer/pcre PHPStan extensions +# +# These can be reused by third party packages by including 'vendor/composer/pcre/extension.neon' +# in your phpstan config + +services: + - + class: Composer\Pcre\PHPStan\PregMatchParameterOutTypeExtension + tags: + - phpstan.staticMethodParameterOutTypeExtension + - + class: Composer\Pcre\PHPStan\PregMatchTypeSpecifyingExtension + tags: + - phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension + - + class: Composer\Pcre\PHPStan\PregReplaceCallbackClosureTypeExtension + tags: + - phpstan.staticMethodParameterClosureTypeExtension + +rules: + - Composer\Pcre\PHPStan\UnsafeStrictGroupsCallRule + - Composer\Pcre\PHPStan\InvalidRegexPatternRule diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchAllResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchAllResult.php new file mode 100644 index 0000000..b22b52d --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchAllResult.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php new file mode 100644 index 0000000..b7ec397 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllStrictGroupsResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php new file mode 100644 index 0000000..032a02c --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchAllWithOffsetsResult +{ + /** + * An array of match group => list of matches, every match being a pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array> + * @phpstan-var array}>> + */ + public $matches; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array> $matches + * @phpstan-param array}>> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchResult.php new file mode 100644 index 0000000..e951a5e --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchResult.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchStrictGroupsResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchStrictGroupsResult.php new file mode 100644 index 0000000..126ee62 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchStrictGroupsResult.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchStrictGroupsResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/MatchWithOffsetsResult.php b/trilhas_poo/vendor/composer/pcre/src/MatchWithOffsetsResult.php new file mode 100644 index 0000000..ba4d4bc --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/MatchWithOffsetsResult.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class MatchWithOffsetsResult +{ + /** + * An array of match group => pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array + * @phpstan-var array}> + */ + public $matches; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + * @param array $matches + * @phpstan-param array}> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/InvalidRegexPatternRule.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/InvalidRegexPatternRule.php new file mode 100644 index 0000000..8a05fb2 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/InvalidRegexPatternRule.php @@ -0,0 +1,142 @@ + + */ +class InvalidRegexPatternRule implements Rule +{ + public function getNodeType(): string + { + return StaticCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $patterns = $this->extractPatterns($node, $scope); + + $errors = []; + foreach ($patterns as $pattern) { + $errorMessage = $this->validatePattern($pattern); + if ($errorMessage === null) { + continue; + } + + $errors[] = RuleErrorBuilder::message(sprintf('Regex pattern is invalid: %s', $errorMessage))->identifier('regexp.pattern')->build(); + } + + return $errors; + } + + /** + * @return string[] + */ + private function extractPatterns(StaticCall $node, Scope $scope): array + { + if (!$node->class instanceof FullyQualified) { + return []; + } + $isRegex = $node->class->toString() === Regex::class; + $isPreg = $node->class->toString() === Preg::class; + if (!$isRegex && !$isPreg) { + return []; + } + if (!$node->name instanceof Node\Identifier || !Preg::isMatch('{^(match|isMatch|grep|replace|split)}', $node->name->name)) { + return []; + } + + $functionName = $node->name->name; + if (!isset($node->getArgs()[0])) { + return []; + } + + $patternNode = $node->getArgs()[0]->value; + $patternType = $scope->getType($patternNode); + + $patternStrings = []; + + foreach ($patternType->getConstantStrings() as $constantStringType) { + if ($functionName === 'replaceCallbackArray') { + continue; + } + + $patternStrings[] = $constantStringType->getValue(); + } + + foreach ($patternType->getConstantArrays() as $constantArrayType) { + if ( + in_array($functionName, [ + 'replace', + 'replaceCallback', + ], true) + ) { + foreach ($constantArrayType->getValueTypes() as $arrayKeyType) { + foreach ($arrayKeyType->getConstantStrings() as $constantString) { + $patternStrings[] = $constantString->getValue(); + } + } + } + + if ($functionName !== 'replaceCallbackArray') { + continue; + } + + foreach ($constantArrayType->getKeyTypes() as $arrayKeyType) { + foreach ($arrayKeyType->getConstantStrings() as $constantString) { + $patternStrings[] = $constantString->getValue(); + } + } + } + + return $patternStrings; + } + + private function validatePattern(string $pattern): ?string + { + try { + $msg = null; + $prev = set_error_handler(function (int $severity, string $message, string $file) use (&$msg): bool { + $msg = preg_replace("#^preg_match(_all)?\\(.*?\\): #", '', $message); + + return true; + }); + + if ($pattern === '') { + return 'Empty string is not a valid regular expression'; + } + + Preg::match($pattern, ''); + if ($msg !== null) { + return $msg; + } + } catch (PcreException $e) { + if ($e->getCode() === PREG_INTERNAL_ERROR && $msg !== null) { + return $msg; + } + + return preg_replace('{.*? failed executing ".*": }', '', $e->getMessage()); + } finally { + restore_error_handler(); + } + + return null; + } + +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchFlags.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchFlags.php new file mode 100644 index 0000000..aa30ab3 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchFlags.php @@ -0,0 +1,70 @@ +getType($flagsArg->value); + + $constantScalars = $flagsType->getConstantScalarValues(); + if ($constantScalars === []) { + return null; + } + + $internalFlagsTypes = []; + foreach ($flagsType->getConstantScalarValues() as $constantScalarValue) { + if (!is_int($constantScalarValue)) { + return null; + } + + $internalFlagsTypes[] = new ConstantIntegerType($constantScalarValue | PREG_UNMATCHED_AS_NULL); + } + return TypeCombinator::union(...$internalFlagsTypes); + } + + static public function removeNullFromMatches(Type $matchesType): Type + { + return TypeTraverser::map($matchesType, static function (Type $type, callable $traverse): Type { + if ($type instanceof UnionType || $type instanceof IntersectionType) { + return $traverse($type); + } + + if ($type instanceof ConstantArrayType) { + return new ConstantArrayType( + $type->getKeyTypes(), + array_map(static function (Type $valueType) use ($traverse): Type { + return $traverse($valueType); + }, $type->getValueTypes()), + $type->getNextAutoIndexes(), + [], + $type->isList() + ); + } + + if ($type instanceof ArrayType) { + return new ArrayType($type->getKeyType(), $traverse($type->getItemType())); + } + + return TypeCombinator::removeNull($type); + }); + } + +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchParameterOutTypeExtension.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchParameterOutTypeExtension.php new file mode 100644 index 0000000..e0d6020 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchParameterOutTypeExtension.php @@ -0,0 +1,65 @@ +regexShapeMatcher = $regexShapeMatcher; + } + + public function isStaticMethodSupported(MethodReflection $methodReflection, ParameterReflection $parameter): bool + { + return + $methodReflection->getDeclaringClass()->getName() === Preg::class + && in_array($methodReflection->getName(), [ + 'match', 'isMatch', 'matchStrictGroups', 'isMatchStrictGroups', + 'matchAll', 'isMatchAll', 'matchAllStrictGroups', 'isMatchAllStrictGroups' + ], true) + && $parameter->getName() === 'matches'; + } + + public function getParameterOutTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, ParameterReflection $parameter, Scope $scope): ?Type + { + $args = $methodCall->getArgs(); + $patternArg = $args[0] ?? null; + $matchesArg = $args[2] ?? null; + $flagsArg = $args[3] ?? null; + + if ( + $patternArg === null || $matchesArg === null + ) { + return null; + } + + $flagsType = PregMatchFlags::getType($flagsArg, $scope); + if ($flagsType === null) { + return null; + } + + if (stripos($methodReflection->getName(), 'matchAll') !== false) { + return $this->regexShapeMatcher->matchAllExpr($patternArg->value, $flagsType, TrinaryLogic::createMaybe(), $scope); + } + + return $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createMaybe(), $scope); + } + +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchTypeSpecifyingExtension.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchTypeSpecifyingExtension.php new file mode 100644 index 0000000..e492c79 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregMatchTypeSpecifyingExtension.php @@ -0,0 +1,125 @@ +regexShapeMatcher = $regexShapeMatcher; + } + + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void + { + $this->typeSpecifier = $typeSpecifier; + } + + public function getClass(): string + { + return Preg::class; + } + + public function isStaticMethodSupported(MethodReflection $methodReflection, StaticCall $node, TypeSpecifierContext $context): bool + { + return in_array($methodReflection->getName(), [ + 'match', 'isMatch', 'matchStrictGroups', 'isMatchStrictGroups', + 'matchAll', 'isMatchAll', 'matchAllStrictGroups', 'isMatchAllStrictGroups' + ], true) + && !$context->null(); + } + + public function specifyTypes(MethodReflection $methodReflection, StaticCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes + { + $args = $node->getArgs(); + $patternArg = $args[0] ?? null; + $subjectArg = $args[1] ?? null; + $matchesArg = $args[2] ?? null; + $flagsArg = $args[3] ?? null; + + $subjectTypes = new SpecifiedTypes(); + if ($patternArg === null) { + return $subjectTypes; + } + + if ( + $subjectArg !== null + && $context->true() + && $scope->getType($subjectArg->value)->isString()->yes() + ) { + $subjectType = $this->regexShapeMatcher->matchSubjectExpr($patternArg->value, $scope); + if ($subjectType !== null) { + $subjectTypes = $this->typeSpecifier->create( + $subjectArg->value, + $subjectType, + $context, + $scope, + )->setRootExpr($node); + } + } + + if ($matchesArg === null) { + return $subjectTypes; + } + + $flagsType = PregMatchFlags::getType($flagsArg, $scope); + if ($flagsType === null) { + return $subjectTypes; + } + + if (stripos($methodReflection->getName(), 'matchAll') !== false) { + $matchedType = $this->regexShapeMatcher->matchAllExpr($patternArg->value, $flagsType, TrinaryLogic::createFromBoolean($context->true()), $scope); + } else { + $matchedType = $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createFromBoolean($context->true()), $scope); + } + + if ($matchedType === null) { + return $subjectTypes; + } + + if ( + in_array($methodReflection->getName(), ['matchStrictGroups', 'isMatchStrictGroups', 'matchAllStrictGroups', 'isMatchAllStrictGroups'], true) + ) { + $matchedType = PregMatchFlags::removeNullFromMatches($matchedType); + } + + $overwrite = false; + if ($context->false()) { + $overwrite = true; + $context = $context->negate(); + } + + $specifiedTypes = $this->typeSpecifier->create( + $matchesArg->value, + $matchedType, + $context, + $scope + )->setRootExpr($node); + + return $subjectTypes->unionWith($overwrite ? $specifiedTypes->setAlwaysOverwriteTypes() : $specifiedTypes); + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregReplaceCallbackClosureTypeExtension.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregReplaceCallbackClosureTypeExtension.php new file mode 100644 index 0000000..7b95367 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/PregReplaceCallbackClosureTypeExtension.php @@ -0,0 +1,91 @@ +regexShapeMatcher = $regexShapeMatcher; + } + + public function isStaticMethodSupported(MethodReflection $methodReflection, ParameterReflection $parameter): bool + { + return in_array($methodReflection->getDeclaringClass()->getName(), [Preg::class, Regex::class], true) + && in_array($methodReflection->getName(), ['replaceCallback', 'replaceCallbackStrictGroups'], true) + && $parameter->getName() === 'replacement'; + } + + public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, ParameterReflection $parameter, Scope $scope): ?Type + { + $args = $methodCall->getArgs(); + $patternArg = $args[0] ?? null; + $flagsArg = $args[5] ?? null; + + if ( + $patternArg === null + ) { + return null; + } + + $flagsType = PregMatchFlags::getType($flagsArg, $scope); + + $matchesType = $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createYes(), $scope); + if ($matchesType === null) { + return null; + } + + if ($methodReflection->getName() === 'replaceCallbackStrictGroups' && count($matchesType->getConstantArrays()) === 1) { + $matchesType = $matchesType->getConstantArrays()[0]; + $matchesType = new ConstantArrayType( + $matchesType->getKeyTypes(), + array_map(static function (Type $valueType): Type { + if (count($valueType->getConstantArrays()) === 1) { + $valueTypeArray = $valueType->getConstantArrays()[0]; + return new ConstantArrayType( + $valueTypeArray->getKeyTypes(), + array_map(static function (Type $valueType): Type { + return TypeCombinator::removeNull($valueType); + }, $valueTypeArray->getValueTypes()), + $valueTypeArray->getNextAutoIndexes(), + [], + $valueTypeArray->isList() + ); + } + return TypeCombinator::removeNull($valueType); + }, $matchesType->getValueTypes()), + $matchesType->getNextAutoIndexes(), + [], + $matchesType->isList() + ); + } + + return new ClosureType( + [ + new NativeParameterReflection($parameter->getName(), $parameter->isOptional(), $matchesType, $parameter->passedByReference(), $parameter->isVariadic(), $parameter->getDefaultValue()), + ], + new StringType() + ); + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PHPStan/UnsafeStrictGroupsCallRule.php b/trilhas_poo/vendor/composer/pcre/src/PHPStan/UnsafeStrictGroupsCallRule.php new file mode 100644 index 0000000..5bced50 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PHPStan/UnsafeStrictGroupsCallRule.php @@ -0,0 +1,112 @@ + + */ +final class UnsafeStrictGroupsCallRule implements Rule +{ + /** + * @var RegexArrayShapeMatcher + */ + private $regexShapeMatcher; + + public function __construct(RegexArrayShapeMatcher $regexShapeMatcher) + { + $this->regexShapeMatcher = $regexShapeMatcher; + } + + public function getNodeType(): string + { + return StaticCall::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node->class instanceof FullyQualified) { + return []; + } + $isRegex = $node->class->toString() === Regex::class; + $isPreg = $node->class->toString() === Preg::class; + if (!$isRegex && !$isPreg) { + return []; + } + if (!$node->name instanceof Node\Identifier || !in_array($node->name->name, ['matchStrictGroups', 'isMatchStrictGroups', 'matchAllStrictGroups', 'isMatchAllStrictGroups'], true)) { + return []; + } + + $args = $node->getArgs(); + if (!isset($args[0])) { + return []; + } + + $patternArg = $args[0] ?? null; + if ($isPreg) { + if (!isset($args[2])) { // no matches set, skip as the matches won't be used anyway + return []; + } + $flagsArg = $args[3] ?? null; + } else { + $flagsArg = $args[2] ?? null; + } + + if ($patternArg === null) { + return []; + } + + $flagsType = PregMatchFlags::getType($flagsArg, $scope); + if ($flagsType === null) { + return []; + } + + $matchedType = $this->regexShapeMatcher->matchExpr($patternArg->value, $flagsType, TrinaryLogic::createYes(), $scope); + if ($matchedType === null) { + return [ + RuleErrorBuilder::message(sprintf('The %s call is potentially unsafe as $matches\' type could not be inferred.', $node->name->name)) + ->identifier('composerPcre.maybeUnsafeStrictGroups') + ->build(), + ]; + } + + if (count($matchedType->getConstantArrays()) === 1) { + $matchedType = $matchedType->getConstantArrays()[0]; + $nullableGroups = []; + foreach ($matchedType->getValueTypes() as $index => $type) { + if (TypeCombinator::containsNull($type)) { + $nullableGroups[] = $matchedType->getKeyTypes()[$index]->getValue(); + } + } + + if (\count($nullableGroups) > 0) { + return [ + RuleErrorBuilder::message(sprintf( + 'The %s call is unsafe as match group%s "%s" %s optional and may be null.', + $node->name->name, + \count($nullableGroups) > 1 ? 's' : '', + implode('", "', $nullableGroups), + \count($nullableGroups) > 1 ? 'are' : 'is' + ))->identifier('composerPcre.unsafeStrictGroups')->build(), + ]; + } + } + + return []; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/PcreException.php b/trilhas_poo/vendor/composer/pcre/src/PcreException.php new file mode 100644 index 0000000..23d9327 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/PcreException.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class PcreException extends \RuntimeException +{ + /** + * @param string $function + * @param string|string[] $pattern + * @return self + */ + public static function fromFunction($function, $pattern) + { + $code = preg_last_error(); + + if (is_array($pattern)) { + $pattern = implode(', ', $pattern); + } + + return new PcreException($function.'(): failed executing "'.$pattern.'": '.self::pcreLastErrorMessage($code), $code); + } + + /** + * @param int $code + * @return string + */ + private static function pcreLastErrorMessage($code) + { + if (function_exists('preg_last_error_msg')) { + return preg_last_error_msg(); + } + + $constants = get_defined_constants(true); + if (!isset($constants['pcre']) || !is_array($constants['pcre'])) { + return 'UNDEFINED_ERROR'; + } + + foreach ($constants['pcre'] as $const => $val) { + if ($val === $code && substr($const, -6) === '_ERROR') { + return $const; + } + } + + return 'UNDEFINED_ERROR'; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/Preg.php b/trilhas_poo/vendor/composer/pcre/src/Preg.php new file mode 100644 index 0000000..98b4d29 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/Preg.php @@ -0,0 +1,430 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class Preg +{ + /** @internal */ + public const ARRAY_MSG = '$subject as an array is not supported. You can use \'foreach\' instead.'; + /** @internal */ + public const INVALID_TYPE_MSG = '$subject must be a string, %s given.'; + + /** + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * + * @param-out array $matches + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + + $result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset); + if ($result === false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + + return $result; + } + + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function matchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + $result = self::match($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatches($pattern, $matchesInternal, 'match'); + + return $result; + } + + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_OFFSET_CAPTURE are always set, no other flags are supported + * @return 0|1 + * + * @param-out array}> $matches + */ + public static function matchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int + { + $result = preg_match($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset); + if ($result === false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + + return $result; + } + + /** + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * + * @param-out array> $matches + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + $result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL, $offset); + if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + + return $result; + } + + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * @throws UnexpectedNullMatchException + * + * @param-out array> $matches + */ + public static function matchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int + { + $result = self::matchAll($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatchAll($pattern, $matchesInternal, 'matchAll'); + + return $result; + } + + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + * @return 0|positive-int + * + * @param-out array}>> $matches + */ + public static function matchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): int + { + self::checkSetOrder($flags); + + $result = preg_match_all($pattern, $subject, $matches, $flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE, $offset); + if (!is_int($result)) { // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + + return $result; + } + + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + * @param int $count Set by method + * + * @param-out int<0, max> $count + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1, ?int &$count = null): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace($pattern, $replacement, $subject, $limit, $count); + if ($result === null) { + throw PcreException::fromFunction('preg_replace', $pattern); + } + + return $result; + } + + /** + * @param string|string[] $pattern + * @param ($flags is PREG_OFFSET_CAPTURE ? (callable(array}>): string) : callable(array): string) $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, ?int &$count = null, int $flags = 0): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace_callback($pattern, $replacement, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL); + if ($result === null) { + throw PcreException::fromFunction('preg_replace_callback', $pattern); + } + + return $result; + } + + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param ($flags is PREG_OFFSET_CAPTURE ? (callable(array}>): string) : callable(array): string) $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackStrictGroups(string $pattern, callable $replacement, $subject, int $limit = -1, ?int &$count = null, int $flags = 0): string + { + return self::replaceCallback($pattern, function (array $matches) use ($pattern, $replacement) { + return $replacement(self::enforceNonNullMatches($pattern, $matches, 'replaceCallback')); + }, $subject, $limit, $count, $flags); + } + + /** + * @param ($flags is PREG_OFFSET_CAPTURE ? (array}>): string>) : array): string>) $pattern + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, ?int &$count = null, int $flags = 0): string + { + if (!is_scalar($subject)) { + if (is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + + throw new \TypeError(sprintf(static::INVALID_TYPE_MSG, gettype($subject))); + } + + $result = preg_replace_callback_array($pattern, $subject, $limit, $count, $flags | PREG_UNMATCHED_AS_NULL); + if ($result === null) { + $pattern = array_keys($pattern); + throw PcreException::fromFunction('preg_replace_callback_array', $pattern); + } + + return $result; + } + + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE + * @return list + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + if (($flags & PREG_SPLIT_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffsets() instead'); + } + + $result = preg_split($pattern, $subject, $limit, $flags); + if ($result === false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + + return $result; + } + + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE is always set + * @return list + * @phpstan-return list}> + */ + public static function splitWithOffsets(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + $result = preg_split($pattern, $subject, $limit, $flags | PREG_SPLIT_OFFSET_CAPTURE); + if ($result === false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + + return $result; + } + + /** + * @template T of string|\Stringable + * @param string $pattern + * @param array $array + * @param int-mask $flags PREG_GREP_INVERT + * @return array + */ + public static function grep(string $pattern, array $array, int $flags = 0): array + { + $result = preg_grep($pattern, $array, $flags); + if ($result === false) { + throw PcreException::fromFunction('preg_grep', $pattern); + } + + return $result; + } + + /** + * Variant of match() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array $matches + */ + public static function isMatch(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) static::match($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of `isMatch()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function isMatchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) self::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchAll() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchAll($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of `isMatchAll()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + return (bool) self::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchWithOffsets() which returns a bool instead of int + * + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}> $matches + */ + public static function isMatchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + + /** + * Variant of matchAllWithOffsets() which returns a bool instead of int + * + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}>> $matches + */ + public static function isMatchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0): bool + { + return (bool) static::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + + private static function checkOffsetCapture(int $flags, string $useFunctionName): void + { + if (($flags & PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the type of $matches, use ' . $useFunctionName . '() instead'); + } + } + + private static function checkSetOrder(int $flags): void + { + if (($flags & PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the type of $matches'); + } + } + + /** + * @param array $matches + * @return array + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatches(string $pattern, array $matches, string $variantMethod): array + { + foreach ($matches as $group => $match) { + if (is_string($match) || (is_array($match) && is_string($match[0]))) { + continue; + } + + throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.'); + } + + /** @var array */ + return $matches; + } + + /** + * @param array> $matches + * @return array> + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatchAll(string $pattern, array $matches, string $variantMethod): array + { + foreach ($matches as $group => $groupMatches) { + foreach ($groupMatches as $match) { + if (null === $match) { + throw new UnexpectedNullMatchException('Pattern "'.$pattern.'" had an unexpected unmatched group "'.$group.'", make sure the pattern always matches or use '.$variantMethod.'() instead.'); + } + } + } + + /** @var array> */ + return $matches; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/Regex.php b/trilhas_poo/vendor/composer/pcre/src/Regex.php new file mode 100644 index 0000000..038cf06 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/Regex.php @@ -0,0 +1,176 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class Regex +{ + /** + * @param non-empty-string $pattern + */ + public static function isMatch(string $pattern, string $subject, int $offset = 0): bool + { + return (bool) Preg::match($pattern, $subject, $matches, 0, $offset); + } + + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function match(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchResult + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + + $count = Preg::match($pattern, $subject, $matches, $flags, $offset); + + return new MatchResult($count, $matches); + } + + /** + * Variant of `match()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchStrictGroupsResult + { + // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups + $count = Preg::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + + return new MatchStrictGroupsResult($count, $matches); + } + + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchWithOffsetsResult + { + $count = Preg::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + + return new MatchWithOffsetsResult($count, $matches); + } + + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function matchAll(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + $count = Preg::matchAll($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllResult($count, $matches); + } + + /** + * Variant of `matchAll()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchAllStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllStrictGroupsResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + + // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups + $count = Preg::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllStrictGroupsResult($count, $matches); + } + + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchAllWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0): MatchAllWithOffsetsResult + { + self::checkSetOrder($flags); + + $count = Preg::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + + return new MatchAllWithOffsetsResult($count, $matches); + } + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1): ReplaceResult + { + $result = Preg::replace($pattern, $replacement, $subject, $limit, $count); + + return new ReplaceResult($count, $result); + } + + /** + * @param string|string[] $pattern + * @param ($flags is PREG_OFFSET_CAPTURE ? (callable(array}>): string) : callable(array): string) $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallback($pattern, $replacement, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param ($flags is PREG_OFFSET_CAPTURE ? (callable(array}>): string) : callable(array): string) $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallbackStrictGroups($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallbackStrictGroups($pattern, $replacement, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + /** + * @param ($flags is PREG_OFFSET_CAPTURE ? (array}>): string>) : array): string>) $pattern + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int $flags = 0): ReplaceResult + { + $result = Preg::replaceCallbackArray($pattern, $subject, $limit, $count, $flags); + + return new ReplaceResult($count, $result); + } + + private static function checkOffsetCapture(int $flags, string $useFunctionName): void + { + if (($flags & PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the return type, use '.$useFunctionName.'() instead'); + } + } + + private static function checkSetOrder(int $flags): void + { + if (($flags & PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the return type'); + } + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/ReplaceResult.php b/trilhas_poo/vendor/composer/pcre/src/ReplaceResult.php new file mode 100644 index 0000000..3384771 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/ReplaceResult.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +final class ReplaceResult +{ + /** + * @readonly + * @var string + */ + public $result; + + /** + * @readonly + * @var 0|positive-int + */ + public $count; + + /** + * @readonly + * @var bool + */ + public $matched; + + /** + * @param 0|positive-int $count + */ + public function __construct(int $count, string $result) + { + $this->count = $count; + $this->matched = (bool) $count; + $this->result = $result; + } +} diff --git a/trilhas_poo/vendor/composer/pcre/src/UnexpectedNullMatchException.php b/trilhas_poo/vendor/composer/pcre/src/UnexpectedNullMatchException.php new file mode 100644 index 0000000..f123828 --- /dev/null +++ b/trilhas_poo/vendor/composer/pcre/src/UnexpectedNullMatchException.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Pcre; + +class UnexpectedNullMatchException extends PcreException +{ + public static function fromFunction($function, $pattern) + { + throw new \LogicException('fromFunction should not be called on '.self::class.', use '.PcreException::class); + } +} diff --git a/trilhas_poo/vendor/composer/semver/CHANGELOG.md b/trilhas_poo/vendor/composer/semver/CHANGELOG.md new file mode 100644 index 0000000..bad46cd --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/CHANGELOG.md @@ -0,0 +1,229 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +### [3.4.3] 2024-09-19 + + * Fixed some type annotations + +### [3.4.2] 2024-07-12 + + * Fixed PHP 5.3 syntax error + +### [3.4.1] 2024-07-12 + + * Fixed normalizeStability's return type to enforce valid stabilities + +### [3.4.0] 2023-08-31 + + * Support larger major version numbers (#149) + +### [3.3.2] 2022-04-01 + + * Fixed handling of non-string values (#134) + +### [3.3.1] 2022-03-16 + + * Fixed possible cache key clash in the CompilingMatcher memoization (#132) + +### [3.3.0] 2022-03-15 + + * Improved performance of CompilingMatcher by memoizing more (#131) + * Added CompilingMatcher::clear to clear all memoization caches + +### [3.2.9] 2022-02-04 + + * Revert #129 (Fixed MultiConstraint with MatchAllConstraint) which caused regressions + +### [3.2.8] 2022-02-04 + + * Updates to latest phpstan / CI by @Seldaek in https://github.com/composer/semver/pull/130 + * Fixed MultiConstraint with MatchAllConstraint by @Toflar in https://github.com/composer/semver/pull/129 + +### [3.2.7] 2022-01-04 + + * Fixed: typo in type definition of Intervals class causing issues with Psalm scanning vendors + +### [3.2.6] 2021-10-25 + + * Fixed: type improvements to parseStability + +### [3.2.5] 2021-05-24 + + * Fixed: issue comparing disjunctive MultiConstraints to conjunctive ones (#127) + * Fixed: added complete type information using phpstan annotations + +### [3.2.4] 2020-11-13 + + * Fixed: code clean-up + +### [3.2.3] 2020-11-12 + + * Fixed: constraints in the form of `X || Y, >=Y.1` and other such complex constructs were in some cases being optimized into a more restrictive constraint + +### [3.2.2] 2020-10-14 + + * Fixed: internal code cleanups + +### [3.2.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [3.2.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [3.1.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 3.0.1 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [3.0.1] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + +### [3.0.0] 2020-05-26 + + * Break: Renamed `EmptyConstraint`, replace it with `MatchAllConstraint` + * Break: Unlikely to affect anyone but strictly speaking a breaking change, `*.*` and such variants will not match all `dev-*` versions anymore, only `*` does + * Break: ConstraintInterface is now considered internal/private and not meant to be implemented by third parties anymore + * Added `Intervals` class to check if a constraint is a subsets of another one, and allow compacting complex MultiConstraints into simpler ones + * Added `CompilingMatcher` class to speed up constraint matching against simple Constraint instances + * Added `MatchAllConstraint` and `MatchNoneConstraint` which match everything and nothing + * Added more advanced optimization of contiguous constraints inside MultiConstraint + * Added tentative support for PHP 8 + * Fixed ConstraintInterface::matches to be commutative in all cases + +### [2.0.0] 2020-04-21 + + * Break: `dev-master`, `dev-trunk` and `dev-default` now normalize to `dev-master`, `dev-trunk` and `dev-default` instead of `9999999-dev` in 1.x + * Break: Removed the deprecated `AbstractConstraint` + * Added `getUpperBound` and `getLowerBound` to ConstraintInterface. They return `Composer\Semver\Constraint\Bound` instances + * Added `MultiConstraint::create` to create the most-optimal form of ConstraintInterface from an array of constraint strings + +### [1.7.2] 2020-12-03 + + * Fixed: Allow installing on php 8 + +### [1.7.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [1.7.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [1.6.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [1.5.2] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + * Fixed: some doctypes + +### [1.5.1] 2020-01-13 + + * Fixed: Parsing of aliased version was not validating the alias to be a valid version + +### [1.5.0] 2019-03-19 + + * Added: some support for date versions (e.g. 201903) in `~` operator + * Fixed: support for stabilities in `~` operator was inconsistent + +### [1.4.2] 2016-08-30 + + * Fixed: collapsing of complex constraints lead to buggy constraints + +### [1.4.1] 2016-06-02 + + * Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38). + +### [1.4.0] 2016-03-30 + + * Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35). + +### [1.3.0] 2016-02-25 + + * Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889). + * Changed: collapse contiguous constraints when possible. + +### [1.2.0] 2015-11-10 + + * Changed: allow multiple numerical identifiers in 'pre-release' version part. + * Changed: add more 'v' prefix support. + +### [1.1.0] 2015-11-03 + + * Changed: dropped redundant `test` namespace. + * Changed: minor adjustment in datetime parsing normalization. + * Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore. + * Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0. + * Changed: `Constraint` is now extensible. + +### [1.0.0] 2015-09-21 + + * Break: `VersionConstraint` renamed to `Constraint`. + * Break: `SpecificConstraint` renamed to `AbstractConstraint`. + * Break: `LinkConstraintInterface` renamed to `ConstraintInterface`. + * Break: `VersionParser::parseNameVersionPairs` was removed. + * Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now. + * Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now. + * Changed: Fixed namespace(s) of test files. + * Changed: `Comparator::compare` no longer throws `InvalidArgumentException`. + * Changed: `Constraint` now throws `InvalidArgumentException`. + +### [0.1.0] 2015-07-23 + + * Added: `Composer\Semver\Comparator`, various methods to compare versions. + * Added: various documents such as README.md, LICENSE, etc. + * Added: configuration files for Git, Travis, php-cs-fixer, phpunit. + * Break: the following namespaces were renamed: + - Namespace: `Composer\Package\Version` -> `Composer\Semver` + - Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint` + - Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver` + - Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint` + * Changed: code style using php-cs-fixer. + +[3.4.3]: https://github.com/composer/semver/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/composer/semver/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/composer/semver/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/composer/semver/compare/3.3.2...3.4.0 +[3.3.2]: https://github.com/composer/semver/compare/3.3.1...3.3.2 +[3.3.1]: https://github.com/composer/semver/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/composer/semver/compare/3.2.9...3.3.0 +[3.2.9]: https://github.com/composer/semver/compare/3.2.8...3.2.9 +[3.2.8]: https://github.com/composer/semver/compare/3.2.7...3.2.8 +[3.2.7]: https://github.com/composer/semver/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/composer/semver/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/composer/semver/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/composer/semver/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/composer/semver/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/composer/semver/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/composer/semver/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/composer/semver/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/composer/semver/compare/3.0.1...3.1.0 +[3.0.1]: https://github.com/composer/semver/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/semver/compare/2.0.0...3.0.0 +[2.0.0]: https://github.com/composer/semver/compare/1.5.1...2.0.0 +[1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2 +[1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1 +[1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0 +[1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0 +[1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0 +[1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0 +[0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0 diff --git a/trilhas_poo/vendor/composer/semver/LICENSE b/trilhas_poo/vendor/composer/semver/LICENSE new file mode 100644 index 0000000..4669758 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/trilhas_poo/vendor/composer/semver/README.md b/trilhas_poo/vendor/composer/semver/README.md new file mode 100644 index 0000000..7677849 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/README.md @@ -0,0 +1,99 @@ +composer/semver +=============== + +Semver (Semantic Versioning) library that offers utilities, version constraint parsing and validation. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +[![Continuous Integration](https://github.com/composer/semver/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/continuous-integration.yml) +[![PHP Lint](https://github.com/composer/semver/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/lint.yml) +[![PHPStan](https://github.com/composer/semver/actions/workflows/phpstan.yml/badge.svg?branch=main)](https://github.com/composer/semver/actions/workflows/phpstan.yml) + +Installation +------------ + +Install the latest version with: + +```bash +composer require composer/semver +``` + + +Requirements +------------ + +* PHP 5.3.2 is required but using the latest version of PHP is highly recommended. + + +Version Comparison +------------------ + +For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md) +article in the documentation section of the [getcomposer.org](https://getcomposer.org) website. + + +Basic usage +----------- + +### Comparator + +The [`Composer\Semver\Comparator`](https://github.com/composer/semver/blob/main/src/Comparator.php) class provides the following methods for comparing versions: + +* greaterThan($v1, $v2) +* greaterThanOrEqualTo($v1, $v2) +* lessThan($v1, $v2) +* lessThanOrEqualTo($v1, $v2) +* equalTo($v1, $v2) +* notEqualTo($v1, $v2) + +Each function takes two version strings as arguments and returns a boolean. For example: + +```php +use Composer\Semver\Comparator; + +Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0 +``` + +### Semver + +The [`Composer\Semver\Semver`](https://github.com/composer/semver/blob/main/src/Semver.php) class provides the following methods: + +* satisfies($version, $constraints) +* satisfiedBy(array $versions, $constraint) +* sort($versions) +* rsort($versions) + +### Intervals + +The [`Composer\Semver\Intervals`](https://github.com/composer/semver/blob/main/src/Intervals.php) static class provides +a few utilities to work with complex constraints or read version intervals from a constraint: + +```php +use Composer\Semver\Intervals; + +// Checks whether $candidate is a subset of $constraint +Intervals::isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint); + +// Checks whether $a and $b have any intersection, equivalent to $a->matches($b) +Intervals::haveIntersections(ConstraintInterface $a, ConstraintInterface $b); + +// Optimizes a complex multi constraint by merging all intervals down to the smallest +// possible multi constraint. The drawbacks are this is not very fast, and the resulting +// multi constraint will have no human readable prettyConstraint configured on it +Intervals::compactConstraint(ConstraintInterface $constraint); + +// Creates an array of numeric intervals and branch constraints representing a given constraint +Intervals::get(ConstraintInterface $constraint); + +// Clears the memoization cache when you are done processing constraints +Intervals::clear() +``` + +See the class docblocks for more details. + + +License +------- + +composer/semver is licensed under the MIT License, see the LICENSE file for details. diff --git a/trilhas_poo/vendor/composer/semver/composer.json b/trilhas_poo/vendor/composer/semver/composer.json new file mode 100644 index 0000000..1fad9e5 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/composer.json @@ -0,0 +1,59 @@ +{ + "name": "composer/semver", + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "type": "library", + "license": "MIT", + "keywords": [ + "semver", + "semantic", + "versioning", + "validation" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3 || ^7", + "phpstan/phpstan": "^1.11" + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\Semver\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor/bin/simple-phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Comparator.php b/trilhas_poo/vendor/composer/semver/src/Comparator.php new file mode 100644 index 0000000..38f483a --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Comparator.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Comparator +{ + /** + * Evaluates the expression: $version1 > $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThan($version1, $version2) + { + return self::compare($version1, '>', $version2); + } + + /** + * Evaluates the expression: $version1 >= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '>=', $version2); + } + + /** + * Evaluates the expression: $version1 < $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThan($version1, $version2) + { + return self::compare($version1, '<', $version2); + } + + /** + * Evaluates the expression: $version1 <= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '<=', $version2); + } + + /** + * Evaluates the expression: $version1 == $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function equalTo($version1, $version2) + { + return self::compare($version1, '==', $version2); + } + + /** + * Evaluates the expression: $version1 != $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function notEqualTo($version1, $version2) + { + return self::compare($version1, '!=', $version2); + } + + /** + * Evaluates the expression: $version1 $operator $version2. + * + * @param string $version1 + * @param string $operator + * @param string $version2 + * + * @return bool + * + * @phpstan-param Constraint::STR_OP_* $operator + */ + public static function compare($version1, $operator, $version2) + { + $constraint = new Constraint($operator, $version2); + + return $constraint->matchSpecific(new Constraint('==', $version1), true); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/CompilingMatcher.php b/trilhas_poo/vendor/composer/semver/src/CompilingMatcher.php new file mode 100644 index 0000000..aea1d3b --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/CompilingMatcher.php @@ -0,0 +1,94 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; +use Composer\Semver\Constraint\ConstraintInterface; + +/** + * Helper class to evaluate constraint by compiling and reusing the code to evaluate + */ +class CompilingMatcher +{ + /** + * @var array + * @phpstan-var array + */ + private static $compiledCheckerCache = array(); + /** + * @var array + * @phpstan-var array + */ + private static $resultCache = array(); + + /** @var bool */ + private static $enabled; + + /** + * @phpstan-var array + */ + private static $transOpInt = array( + Constraint::OP_EQ => Constraint::STR_OP_EQ, + Constraint::OP_LT => Constraint::STR_OP_LT, + Constraint::OP_LE => Constraint::STR_OP_LE, + Constraint::OP_GT => Constraint::STR_OP_GT, + Constraint::OP_GE => Constraint::STR_OP_GE, + Constraint::OP_NE => Constraint::STR_OP_NE, + ); + + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$resultCache = array(); + self::$compiledCheckerCache = array(); + } + + /** + * Evaluates the expression: $constraint match $operator $version + * + * @param ConstraintInterface $constraint + * @param int $operator + * @phpstan-param Constraint::OP_* $operator + * @param string $version + * + * @return bool + */ + public static function match(ConstraintInterface $constraint, $operator, $version) + { + $resultCacheKey = $operator.$constraint.';'.$version; + + if (isset(self::$resultCache[$resultCacheKey])) { + return self::$resultCache[$resultCacheKey]; + } + + if (self::$enabled === null) { + self::$enabled = !\in_array('eval', explode(',', (string) ini_get('disable_functions')), true); + } + if (!self::$enabled) { + return self::$resultCache[$resultCacheKey] = $constraint->matches(new Constraint(self::$transOpInt[$operator], $version)); + } + + $cacheKey = $operator.$constraint; + if (!isset(self::$compiledCheckerCache[$cacheKey])) { + $code = $constraint->compile($operator); + self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};'); + } else { + $function = self::$compiledCheckerCache[$cacheKey]; + } + + return self::$resultCache[$resultCacheKey] = $function($version, strpos($version, 'dev-') === 0); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/Bound.php b/trilhas_poo/vendor/composer/semver/src/Constraint/Bound.php new file mode 100644 index 0000000..7effb11 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/Bound.php @@ -0,0 +1,122 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +class Bound +{ + /** + * @var string + */ + private $version; + + /** + * @var bool + */ + private $isInclusive; + + /** + * @param string $version + * @param bool $isInclusive + */ + public function __construct($version, $isInclusive) + { + $this->version = $version; + $this->isInclusive = $isInclusive; + } + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @return bool + */ + public function isInclusive() + { + return $this->isInclusive; + } + + /** + * @return bool + */ + public function isZero() + { + return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive(); + } + + /** + * @return bool + */ + public function isPositiveInfinity() + { + return $this->getVersion() === PHP_INT_MAX.'.0.0.0' && !$this->isInclusive(); + } + + /** + * Compares a bound to another with a given operator. + * + * @param Bound $other + * @param string $operator + * + * @return bool + */ + public function compareTo(Bound $other, $operator) + { + if (!\in_array($operator, array('<', '>'), true)) { + throw new \InvalidArgumentException('Does not support any other operator other than > or <.'); + } + + // If they are the same it doesn't matter + if ($this == $other) { + return false; + } + + $compareResult = version_compare($this->getVersion(), $other->getVersion()); + + // Not the same version means we don't need to check if the bounds are inclusive or not + if (0 !== $compareResult) { + return (('>' === $operator) ? 1 : -1) === $compareResult; + } + + // Question we're answering here is "am I higher than $other?" + return '>' === $operator ? $other->isInclusive() : !$other->isInclusive(); + } + + public function __toString() + { + return sprintf( + '%s [%s]', + $this->getVersion(), + $this->isInclusive() ? 'inclusive' : 'exclusive' + ); + } + + /** + * @return self + */ + public static function zero() + { + return new Bound('0.0.0.0-dev', true); + } + + /** + * @return self + */ + public static function positiveInfinity() + { + return new Bound(PHP_INT_MAX.'.0.0.0', false); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/Constraint.php b/trilhas_poo/vendor/composer/semver/src/Constraint/Constraint.php new file mode 100644 index 0000000..dc39482 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/Constraint.php @@ -0,0 +1,435 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines a constraint. + */ +class Constraint implements ConstraintInterface +{ + /* operator integer values */ + const OP_EQ = 0; + const OP_LT = 1; + const OP_LE = 2; + const OP_GT = 3; + const OP_GE = 4; + const OP_NE = 5; + + /* operator string values */ + const STR_OP_EQ = '=='; + const STR_OP_EQ_ALT = '='; + const STR_OP_LT = '<'; + const STR_OP_LE = '<='; + const STR_OP_GT = '>'; + const STR_OP_GE = '>='; + const STR_OP_NE = '!='; + const STR_OP_NE_ALT = '<>'; + + /** + * Operator to integer translation table. + * + * @var array + * @phpstan-var array + */ + private static $transOpStr = array( + '=' => self::OP_EQ, + '==' => self::OP_EQ, + '<' => self::OP_LT, + '<=' => self::OP_LE, + '>' => self::OP_GT, + '>=' => self::OP_GE, + '<>' => self::OP_NE, + '!=' => self::OP_NE, + ); + + /** + * Integer to operator translation table. + * + * @var array + * @phpstan-var array + */ + private static $transOpInt = array( + self::OP_EQ => '==', + self::OP_LT => '<', + self::OP_LE => '<=', + self::OP_GT => '>', + self::OP_GE => '>=', + self::OP_NE => '!=', + ); + + /** + * @var int + * @phpstan-var self::OP_* + */ + protected $operator; + + /** @var string */ + protected $version; + + /** @var string|null */ + protected $prettyString; + + /** @var Bound */ + protected $lowerBound; + + /** @var Bound */ + protected $upperBound; + + /** + * Sets operator and version to compare with. + * + * @param string $operator + * @param string $version + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @phpstan-param self::STR_OP_* $operator + */ + public function __construct($operator, $version) + { + if (!isset(self::$transOpStr[$operator])) { + throw new \InvalidArgumentException(sprintf( + 'Invalid operator "%s" given, expected one of: %s', + $operator, + implode(', ', self::getSupportedOperators()) + )); + } + + $this->operator = self::$transOpStr[$operator]; + $this->version = $version; + } + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @return string + * + * @phpstan-return self::STR_OP_* + */ + public function getOperator() + { + return self::$transOpInt[$this->operator]; + } + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if ($provider instanceof self) { + return $this->matchSpecific($provider); + } + + // turn matching around to find a match + return $provider->matches($this); + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return $this->__toString(); + } + + /** + * Get all supported comparison operators. + * + * @return array + * + * @phpstan-return list + */ + public static function getSupportedOperators() + { + return array_keys(self::$transOpStr); + } + + /** + * @param string $operator + * @return int + * + * @phpstan-param self::STR_OP_* $operator + * @phpstan-return self::OP_* + */ + public static function getOperatorConstant($operator) + { + return self::$transOpStr[$operator]; + } + + /** + * @param string $a + * @param string $b + * @param string $operator + * @param bool $compareBranches + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @return bool + * + * @phpstan-param self::STR_OP_* $operator + */ + public function versionCompare($a, $b, $operator, $compareBranches = false) + { + if (!isset(self::$transOpStr[$operator])) { + throw new \InvalidArgumentException(sprintf( + 'Invalid operator "%s" given, expected one of: %s', + $operator, + implode(', ', self::getSupportedOperators()) + )); + } + + $aIsBranch = strpos($a, 'dev-') === 0; + $bIsBranch = strpos($b, 'dev-') === 0; + + if ($operator === '!=' && ($aIsBranch || $bIsBranch)) { + return $a !== $b; + } + + if ($aIsBranch && $bIsBranch) { + return $operator === '==' && $a === $b; + } + + // when branches are not comparable, we make sure dev branches never match anything + if (!$compareBranches && ($aIsBranch || $bIsBranch)) { + return false; + } + + return \version_compare($a, $b, $operator); + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + if (strpos($this->version, 'dev-') === 0) { + if (self::OP_EQ === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('$b && $v === %s', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return sprintf('!$b || $v !== %s', \var_export($this->version, true)); + } + return 'false'; + } + + if (self::OP_NE === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('!$b || $v !== %s', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return 'true'; + } + return '!$b'; + } + + return 'false'; + } + + if (self::OP_EQ === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('\version_compare($v, %s, \'==\')', \var_export($this->version, true)); + } + if (self::OP_NE === $otherOperator) { + return sprintf('$b || \version_compare($v, %s, \'!=\')', \var_export($this->version, true)); + } + + return sprintf('!$b && \version_compare(%s, $v, \'%s\')', \var_export($this->version, true), self::$transOpInt[$otherOperator]); + } + + if (self::OP_NE === $this->operator) { + if (self::OP_EQ === $otherOperator) { + return sprintf('$b || (!$b && \version_compare($v, %s, \'!=\'))', \var_export($this->version, true)); + } + + if (self::OP_NE === $otherOperator) { + return 'true'; + } + return '!$b'; + } + + if (self::OP_LT === $this->operator || self::OP_LE === $this->operator) { + if (self::OP_LT === $otherOperator || self::OP_LE === $otherOperator) { + return '!$b'; + } + } else { // $this->operator must be self::OP_GT || self::OP_GE here + if (self::OP_GT === $otherOperator || self::OP_GE === $otherOperator) { + return '!$b'; + } + } + + if (self::OP_NE === $otherOperator) { + return 'true'; + } + + $codeComparison = sprintf('\version_compare($v, %s, \'%s\')', \var_export($this->version, true), self::$transOpInt[$this->operator]); + if ($this->operator === self::OP_LE) { + if ($otherOperator === self::OP_GT) { + return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison; + } + } elseif ($this->operator === self::OP_GE) { + if ($otherOperator === self::OP_LT) { + return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison; + } + } + + return sprintf('!$b && %s', $codeComparison); + } + + /** + * @param Constraint $provider + * @param bool $compareBranches + * + * @return bool + */ + public function matchSpecific(Constraint $provider, $compareBranches = false) + { + $noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]); + $providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]); + + $isEqualOp = self::OP_EQ === $this->operator; + $isNonEqualOp = self::OP_NE === $this->operator; + $isProviderEqualOp = self::OP_EQ === $provider->operator; + $isProviderNonEqualOp = self::OP_NE === $provider->operator; + + // '!=' operator is match when other operator is not '==' operator or version is not match + // these kinds of comparisons always have a solution + if ($isNonEqualOp || $isProviderNonEqualOp) { + if ($isNonEqualOp && !$isProviderNonEqualOp && !$isProviderEqualOp && strpos($provider->version, 'dev-') === 0) { + return false; + } + + if ($isProviderNonEqualOp && !$isNonEqualOp && !$isEqualOp && strpos($this->version, 'dev-') === 0) { + return false; + } + + if (!$isEqualOp && !$isProviderEqualOp) { + return true; + } + return $this->versionCompare($provider->version, $this->version, '!=', $compareBranches); + } + + // an example for the condition is <= 2.0 & < 1.0 + // these kinds of comparisons always have a solution + if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) { + return !(strpos($this->version, 'dev-') === 0 || strpos($provider->version, 'dev-') === 0); + } + + $version1 = $isEqualOp ? $this->version : $provider->version; + $version2 = $isEqualOp ? $provider->version : $this->version; + $operator = $isEqualOp ? $provider->operator : $this->operator; + + if ($this->versionCompare($version1, $version2, self::$transOpInt[$operator], $compareBranches)) { + // special case, e.g. require >= 1.0 and provide < 1.0 + // 1.0 >= 1.0 but 1.0 is outside of the provided interval + + return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp + && self::$transOpInt[$this->operator] !== $noEqualOp + && \version_compare($provider->version, $this->version, '==')); + } + + return false; + } + + /** + * @return string + */ + public function __toString() + { + return self::$transOpInt[$this->operator] . ' ' . $this->version; + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + + return $this->lowerBound; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + + return $this->upperBound; + } + + /** + * @return void + */ + private function extractBounds() + { + if (null !== $this->lowerBound) { + return; + } + + // Branches + if (strpos($this->version, 'dev-') === 0) { + $this->lowerBound = Bound::zero(); + $this->upperBound = Bound::positiveInfinity(); + + return; + } + + switch ($this->operator) { + case self::OP_EQ: + $this->lowerBound = new Bound($this->version, true); + $this->upperBound = new Bound($this->version, true); + break; + case self::OP_LT: + $this->lowerBound = Bound::zero(); + $this->upperBound = new Bound($this->version, false); + break; + case self::OP_LE: + $this->lowerBound = Bound::zero(); + $this->upperBound = new Bound($this->version, true); + break; + case self::OP_GT: + $this->lowerBound = new Bound($this->version, false); + $this->upperBound = Bound::positiveInfinity(); + break; + case self::OP_GE: + $this->lowerBound = new Bound($this->version, true); + $this->upperBound = Bound::positiveInfinity(); + break; + case self::OP_NE: + $this->lowerBound = Bound::zero(); + $this->upperBound = Bound::positiveInfinity(); + break; + } + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/ConstraintInterface.php b/trilhas_poo/vendor/composer/semver/src/Constraint/ConstraintInterface.php new file mode 100644 index 0000000..389b935 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/ConstraintInterface.php @@ -0,0 +1,75 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * DO NOT IMPLEMENT this interface. It is only meant for usage as a type hint + * in libraries relying on composer/semver but creating your own constraint class + * that implements this interface is not a supported use case and will cause the + * composer/semver components to return unexpected results. + */ +interface ConstraintInterface +{ + /** + * Checks whether the given constraint intersects in any way with this constraint + * + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider); + + /** + * Provides a compiled version of the constraint for the given operator + * The compiled version must be a PHP expression. + * Executor of compile version must provide 2 variables: + * - $v = the string version to compare with + * - $b = whether or not the version is a non-comparable branch (starts with "dev-") + * + * @see Constraint::OP_* for the list of available operators. + * @example return '!$b && version_compare($v, '1.0', '>')'; + * + * @param int $otherOperator one Constraint::OP_* + * + * @return string + * + * @phpstan-param Constraint::OP_* $otherOperator + */ + public function compile($otherOperator); + + /** + * @return Bound + */ + public function getUpperBound(); + + /** + * @return Bound + */ + public function getLowerBound(); + + /** + * @return string + */ + public function getPrettyString(); + + /** + * @param string|null $prettyString + * + * @return void + */ + public function setPrettyString($prettyString); + + /** + * @return string + */ + public function __toString(); +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/MatchAllConstraint.php b/trilhas_poo/vendor/composer/semver/src/Constraint/MatchAllConstraint.php new file mode 100644 index 0000000..5e51af9 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/MatchAllConstraint.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines the absence of a constraint. + * + * This constraint matches everything. + */ +class MatchAllConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return true; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'true'; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + return '*'; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return Bound::positiveInfinity(); + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return Bound::zero(); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php b/trilhas_poo/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php new file mode 100644 index 0000000..dadcf62 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php @@ -0,0 +1,83 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Blackhole of constraints, nothing escapes it + */ +class MatchNoneConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return false; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'false'; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + return '[]'; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return new Bound('0.0.0.0-dev', false); + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return new Bound('0.0.0.0-dev', false); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Constraint/MultiConstraint.php b/trilhas_poo/vendor/composer/semver/src/Constraint/MultiConstraint.php new file mode 100644 index 0000000..1f4c006 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Constraint/MultiConstraint.php @@ -0,0 +1,325 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver\Constraint; + +/** + * Defines a conjunctive or disjunctive set of constraints. + */ +class MultiConstraint implements ConstraintInterface +{ + /** + * @var ConstraintInterface[] + * @phpstan-var non-empty-array + */ + protected $constraints; + + /** @var string|null */ + protected $prettyString; + + /** @var string|null */ + protected $string; + + /** @var bool */ + protected $conjunctive; + + /** @var Bound|null */ + protected $lowerBound; + + /** @var Bound|null */ + protected $upperBound; + + /** + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @throws \InvalidArgumentException If less than 2 constraints are passed + */ + public function __construct(array $constraints, $conjunctive = true) + { + if (\count($constraints) < 2) { + throw new \InvalidArgumentException( + 'Must provide at least two constraints for a MultiConstraint. Use '. + 'the regular Constraint class for one constraint only or MatchAllConstraint for none. You may use '. + 'MultiConstraint::create() which optimizes and handles those cases automatically.' + ); + } + + $this->constraints = $constraints; + $this->conjunctive = $conjunctive; + } + + /** + * @return ConstraintInterface[] + */ + public function getConstraints() + { + return $this->constraints; + } + + /** + * @return bool + */ + public function isConjunctive() + { + return $this->conjunctive; + } + + /** + * @return bool + */ + public function isDisjunctive() + { + return !$this->conjunctive; + } + + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + $parts = array(); + foreach ($this->constraints as $constraint) { + $code = $constraint->compile($otherOperator); + if ($code === 'true') { + if (!$this->conjunctive) { + return 'true'; + } + } elseif ($code === 'false') { + if ($this->conjunctive) { + return 'false'; + } + } else { + $parts[] = '('.$code.')'; + } + } + + if (!$parts) { + return $this->conjunctive ? 'true' : 'false'; + } + + return $this->conjunctive ? implode('&&', $parts) : implode('||', $parts); + } + + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if (false === $this->conjunctive) { + foreach ($this->constraints as $constraint) { + if ($provider->matches($constraint)) { + return true; + } + } + + return false; + } + + // when matching a conjunctive and a disjunctive multi constraint we have to iterate over the disjunctive one + // otherwise we'd return true if different parts of the disjunctive constraint match the conjunctive one + // which would lead to incorrect results, e.g. [>1 and <2] would match [<1 or >2] although they do not intersect + if ($provider instanceof MultiConstraint && $provider->isDisjunctive()) { + return $provider->matches($this); + } + + foreach ($this->constraints as $constraint) { + if (!$provider->matches($constraint)) { + return false; + } + } + + return true; + } + + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + + return (string) $this; + } + + /** + * {@inheritDoc} + */ + public function __toString() + { + if ($this->string !== null) { + return $this->string; + } + + $constraints = array(); + foreach ($this->constraints as $constraint) { + $constraints[] = (string) $constraint; + } + + return $this->string = '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']'; + } + + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + + if (null === $this->lowerBound) { + throw new \LogicException('extractBounds should have populated the lowerBound property'); + } + + return $this->lowerBound; + } + + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + + if (null === $this->upperBound) { + throw new \LogicException('extractBounds should have populated the upperBound property'); + } + + return $this->upperBound; + } + + /** + * Tries to optimize the constraints as much as possible, meaning + * reducing/collapsing congruent constraints etc. + * Does not necessarily return a MultiConstraint instance if + * things can be reduced to a simple constraint + * + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @return ConstraintInterface + */ + public static function create(array $constraints, $conjunctive = true) + { + if (0 === \count($constraints)) { + return new MatchAllConstraint(); + } + + if (1 === \count($constraints)) { + return $constraints[0]; + } + + $optimized = self::optimizeConstraints($constraints, $conjunctive); + if ($optimized !== null) { + list($constraints, $conjunctive) = $optimized; + if (\count($constraints) === 1) { + return $constraints[0]; + } + } + + return new self($constraints, $conjunctive); + } + + /** + * @param ConstraintInterface[] $constraints + * @param bool $conjunctive + * @return ?array + * + * @phpstan-return array{0: list, 1: bool}|null + */ + private static function optimizeConstraints(array $constraints, $conjunctive) + { + // parse the two OR groups and if they are contiguous we collapse + // them into one constraint + // [>= 1 < 2] || [>= 2 < 3] || [>= 3 < 4] => [>= 1 < 4] + if (!$conjunctive) { + $left = $constraints[0]; + $mergedConstraints = array(); + $optimized = false; + for ($i = 1, $l = \count($constraints); $i < $l; $i++) { + $right = $constraints[$i]; + if ( + $left instanceof self + && $left->conjunctive + && $right instanceof self + && $right->conjunctive + && \count($left->constraints) === 2 + && \count($right->constraints) === 2 + && ($left0 = (string) $left->constraints[0]) + && $left0[0] === '>' && $left0[1] === '=' + && ($left1 = (string) $left->constraints[1]) + && $left1[0] === '<' + && ($right0 = (string) $right->constraints[0]) + && $right0[0] === '>' && $right0[1] === '=' + && ($right1 = (string) $right->constraints[1]) + && $right1[0] === '<' + && substr($left1, 2) === substr($right0, 3) + ) { + $optimized = true; + $left = new MultiConstraint( + array( + $left->constraints[0], + $right->constraints[1], + ), + true); + } else { + $mergedConstraints[] = $left; + $left = $right; + } + } + if ($optimized) { + $mergedConstraints[] = $left; + return array($mergedConstraints, false); + } + } + + // TODO: Here's the place to put more optimizations + + return null; + } + + /** + * @return void + */ + private function extractBounds() + { + if (null !== $this->lowerBound) { + return; + } + + foreach ($this->constraints as $constraint) { + if (null === $this->lowerBound || null === $this->upperBound) { + $this->lowerBound = $constraint->getLowerBound(); + $this->upperBound = $constraint->getUpperBound(); + continue; + } + + if ($constraint->getLowerBound()->compareTo($this->lowerBound, $this->isConjunctive() ? '>' : '<')) { + $this->lowerBound = $constraint->getLowerBound(); + } + + if ($constraint->getUpperBound()->compareTo($this->upperBound, $this->isConjunctive() ? '<' : '>')) { + $this->upperBound = $constraint->getUpperBound(); + } + } + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Interval.php b/trilhas_poo/vendor/composer/semver/src/Interval.php new file mode 100644 index 0000000..43d5a4f --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Interval.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Interval +{ + /** @var Constraint */ + private $start; + /** @var Constraint */ + private $end; + + public function __construct(Constraint $start, Constraint $end) + { + $this->start = $start; + $this->end = $end; + } + + /** + * @return Constraint + */ + public function getStart() + { + return $this->start; + } + + /** + * @return Constraint + */ + public function getEnd() + { + return $this->end; + } + + /** + * @return Constraint + */ + public static function fromZero() + { + static $zero; + + if (null === $zero) { + $zero = new Constraint('>=', '0.0.0.0-dev'); + } + + return $zero; + } + + /** + * @return Constraint + */ + public static function untilPositiveInfinity() + { + static $positiveInfinity; + + if (null === $positiveInfinity) { + $positiveInfinity = new Constraint('<', PHP_INT_MAX.'.0.0.0'); + } + + return $positiveInfinity; + } + + /** + * @return self + */ + public static function any() + { + return new self(self::fromZero(), self::untilPositiveInfinity()); + } + + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function anyDev() + { + // any == exclude nothing + return array('names' => array(), 'exclude' => true); + } + + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function noDev() + { + // nothing == no names included + return array('names' => array(), 'exclude' => false); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Intervals.php b/trilhas_poo/vendor/composer/semver/src/Intervals.php new file mode 100644 index 0000000..d889d0a --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Intervals.php @@ -0,0 +1,478 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; +use Composer\Semver\Constraint\ConstraintInterface; +use Composer\Semver\Constraint\MatchAllConstraint; +use Composer\Semver\Constraint\MatchNoneConstraint; +use Composer\Semver\Constraint\MultiConstraint; + +/** + * Helper class generating intervals from constraints + * + * This contains utilities for: + * + * - compacting an existing constraint which can be used to combine several into one + * by creating a MultiConstraint out of the many constraints you have. + * + * - checking whether one subset is a subset of another. + * + * Note: You should call clear to free memoization memory usage when you are done using this class + */ +class Intervals +{ + /** + * @phpstan-var array + */ + private static $intervalsCache = array(); + + /** + * @phpstan-var array + */ + private static $opSortOrder = array( + '>=' => -3, + '<' => -2, + '>' => 2, + '<=' => 3, + ); + + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$intervalsCache = array(); + } + + /** + * Checks whether $candidate is a subset of $constraint + * + * @return bool + */ + public static function isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint) + { + if ($constraint instanceof MatchAllConstraint) { + return true; + } + + if ($candidate instanceof MatchNoneConstraint || $constraint instanceof MatchNoneConstraint) { + return false; + } + + $intersectionIntervals = self::get(new MultiConstraint(array($candidate, $constraint), true)); + $candidateIntervals = self::get($candidate); + if (\count($intersectionIntervals['numeric']) !== \count($candidateIntervals['numeric'])) { + return false; + } + + foreach ($intersectionIntervals['numeric'] as $index => $interval) { + if (!isset($candidateIntervals['numeric'][$index])) { + return false; + } + + if ((string) $candidateIntervals['numeric'][$index]->getStart() !== (string) $interval->getStart()) { + return false; + } + + if ((string) $candidateIntervals['numeric'][$index]->getEnd() !== (string) $interval->getEnd()) { + return false; + } + } + + if ($intersectionIntervals['branches']['exclude'] !== $candidateIntervals['branches']['exclude']) { + return false; + } + if (\count($intersectionIntervals['branches']['names']) !== \count($candidateIntervals['branches']['names'])) { + return false; + } + foreach ($intersectionIntervals['branches']['names'] as $index => $name) { + if ($name !== $candidateIntervals['branches']['names'][$index]) { + return false; + } + } + + return true; + } + + /** + * Checks whether $a and $b have any intersection, equivalent to $a->matches($b) + * + * @return bool + */ + public static function haveIntersections(ConstraintInterface $a, ConstraintInterface $b) + { + if ($a instanceof MatchAllConstraint || $b instanceof MatchAllConstraint) { + return true; + } + + if ($a instanceof MatchNoneConstraint || $b instanceof MatchNoneConstraint) { + return false; + } + + $intersectionIntervals = self::generateIntervals(new MultiConstraint(array($a, $b), true), true); + + return \count($intersectionIntervals['numeric']) > 0 || $intersectionIntervals['branches']['exclude'] || \count($intersectionIntervals['branches']['names']) > 0; + } + + /** + * Attempts to optimize a MultiConstraint + * + * When merging MultiConstraints together they can get very large, this will + * compact it by looking at the real intervals covered by all the constraints + * and then creates a new constraint containing only the smallest amount of rules + * to match the same intervals. + * + * @return ConstraintInterface + */ + public static function compactConstraint(ConstraintInterface $constraint) + { + if (!$constraint instanceof MultiConstraint) { + return $constraint; + } + + $intervals = self::generateIntervals($constraint); + $constraints = array(); + $hasNumericMatchAll = false; + + if (\count($intervals['numeric']) === 1 && (string) $intervals['numeric'][0]->getStart() === (string) Interval::fromZero() && (string) $intervals['numeric'][0]->getEnd() === (string) Interval::untilPositiveInfinity()) { + $constraints[] = $intervals['numeric'][0]->getStart(); + $hasNumericMatchAll = true; + } else { + $unEqualConstraints = array(); + for ($i = 0, $count = \count($intervals['numeric']); $i < $count; $i++) { + $interval = $intervals['numeric'][$i]; + + // if current interval ends with < N and next interval begins with > N we can swap this out for != N + // but this needs to happen as a conjunctive expression together with the start of the current interval + // and end of next interval, so [>=M, N, [>=M, !=N, getEnd()->getOperator() === '<' && $i+1 < $count) { + $nextInterval = $intervals['numeric'][$i+1]; + if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') { + // only add a start if we didn't already do so, can be skipped if we're looking at second + // interval in [>=M, N, P, =M, !=N] already and we only want to add !=P right now + if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) { + $unEqualConstraints[] = $interval->getStart(); + } + $unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion()); + continue; + } + } + + if (\count($unEqualConstraints) > 0) { + // this is where the end of the following interval of a != constraint is added as explained above + if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) { + $unEqualConstraints[] = $interval->getEnd(); + } + + // count is 1 if entire constraint is just one != expression + if (\count($unEqualConstraints) > 1) { + $constraints[] = new MultiConstraint($unEqualConstraints, true); + } else { + $constraints[] = $unEqualConstraints[0]; + } + + $unEqualConstraints = array(); + continue; + } + + // convert back >= x - <= x intervals to == x + if ($interval->getStart()->getVersion() === $interval->getEnd()->getVersion() && $interval->getStart()->getOperator() === '>=' && $interval->getEnd()->getOperator() === '<=') { + $constraints[] = new Constraint('==', $interval->getStart()->getVersion()); + continue; + } + + if ((string) $interval->getStart() === (string) Interval::fromZero()) { + $constraints[] = $interval->getEnd(); + } elseif ((string) $interval->getEnd() === (string) Interval::untilPositiveInfinity()) { + $constraints[] = $interval->getStart(); + } else { + $constraints[] = new MultiConstraint(array($interval->getStart(), $interval->getEnd()), true); + } + } + } + + $devConstraints = array(); + + if (0 === \count($intervals['branches']['names'])) { + if ($intervals['branches']['exclude']) { + if ($hasNumericMatchAll) { + return new MatchAllConstraint; + } + // otherwise constraint should contain a != operator and already cover this + } + } else { + foreach ($intervals['branches']['names'] as $branchName) { + if ($intervals['branches']['exclude']) { + $devConstraints[] = new Constraint('!=', $branchName); + } else { + $devConstraints[] = new Constraint('==', $branchName); + } + } + + // excluded branches, e.g. != dev-foo are conjunctive with the interval, so + // > 2.0 != dev-foo must return a conjunctive constraint + if ($intervals['branches']['exclude']) { + if (\count($constraints) > 1) { + return new MultiConstraint(array_merge( + array(new MultiConstraint($constraints, false)), + $devConstraints + ), true); + } + + if (\count($constraints) === 1 && (string)$constraints[0] === (string)Interval::fromZero()) { + if (\count($devConstraints) > 1) { + return new MultiConstraint($devConstraints, true); + } + return $devConstraints[0]; + } + + return new MultiConstraint(array_merge($constraints, $devConstraints), true); + } + + // otherwise devConstraints contains a list of == operators for branches which are disjunctive with the + // rest of the constraint + $constraints = array_merge($constraints, $devConstraints); + } + + if (\count($constraints) > 1) { + return new MultiConstraint($constraints, false); + } + + if (\count($constraints) === 1) { + return $constraints[0]; + } + + return new MatchNoneConstraint; + } + + /** + * Creates an array of numeric intervals and branch constraints representing a given constraint + * + * if the returned numeric array is empty it means the constraint matches nothing in the numeric range (0 - +inf) + * if the returned branches array is empty it means no dev-* versions are matched + * if a constraint matches all possible dev-* versions, branches will contain Interval::anyDev() + * + * @return array + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + public static function get(ConstraintInterface $constraint) + { + $key = (string) $constraint; + + if (!isset(self::$intervalsCache[$key])) { + self::$intervalsCache[$key] = self::generateIntervals($constraint); + } + + return self::$intervalsCache[$key]; + } + + /** + * @param bool $stopOnFirstValidInterval + * + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + private static function generateIntervals(ConstraintInterface $constraint, $stopOnFirstValidInterval = false) + { + if ($constraint instanceof MatchAllConstraint) { + return array('numeric' => array(new Interval(Interval::fromZero(), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev()); + } + + if ($constraint instanceof MatchNoneConstraint) { + return array('numeric' => array(), 'branches' => array('names' => array(), 'exclude' => false)); + } + + if ($constraint instanceof Constraint) { + return self::generateSingleConstraintIntervals($constraint); + } + + if (!$constraint instanceof MultiConstraint) { + throw new \UnexpectedValueException('The constraint passed in should be an MatchAllConstraint, Constraint or MultiConstraint instance, got '.\get_class($constraint).'.'); + } + + $constraints = $constraint->getConstraints(); + + $numericGroups = array(); + $constraintBranches = array(); + foreach ($constraints as $c) { + $res = self::get($c); + $numericGroups[] = $res['numeric']; + $constraintBranches[] = $res['branches']; + } + + if ($constraint->isDisjunctive()) { + $branches = Interval::noDev(); + foreach ($constraintBranches as $b) { + if ($b['exclude']) { + if ($branches['exclude']) { + // disjunctive constraint, so only exclude what's excluded in all constraints + // !=a,!=b || !=b,!=c => !=b + $branches['names'] = array_intersect($branches['names'], $b['names']); + } else { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // (==b || ==c) || !=a,!=b => !=a + $branches['exclude'] = true; + $branches['names'] = array_diff($b['names'], $branches['names']); + } + } else { + if ($branches['exclude']) { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // !=a,!=b || (==b || ==c) => !=a + $branches['names'] = array_diff($branches['names'], $b['names']); + } else { + // disjunctive constraint, so just add all the other branches + // (==a || ==b) || ==c => ==a || ==b || ==c + $branches['names'] = array_merge($branches['names'], $b['names']); + } + } + } + } else { + $branches = Interval::anyDev(); + foreach ($constraintBranches as $b) { + if ($b['exclude']) { + if ($branches['exclude']) { + // conjunctive, so just add all branch names to be excluded + // !=a && !=b => !=a,!=b + $branches['names'] = array_merge($branches['names'], $b['names']); + } else { + // conjunctive, so only keep included names which are not excluded + // (==a||==c) && !=a,!=b => ==c + $branches['names'] = array_diff($branches['names'], $b['names']); + } + } else { + if ($branches['exclude']) { + // conjunctive, so only keep included names which are not excluded + // !=a,!=b && (==a||==c) => ==c + $branches['names'] = array_diff($b['names'], $branches['names']); + $branches['exclude'] = false; + } else { + // conjunctive, so only keep names that are included in both + // (==a||==b) && (==a||==c) => ==a + $branches['names'] = array_intersect($branches['names'], $b['names']); + } + } + } + } + + $branches['names'] = array_unique($branches['names']); + + if (\count($numericGroups) === 1) { + return array('numeric' => $numericGroups[0], 'branches' => $branches); + } + + $borders = array(); + foreach ($numericGroups as $group) { + foreach ($group as $interval) { + $borders[] = array('version' => $interval->getStart()->getVersion(), 'operator' => $interval->getStart()->getOperator(), 'side' => 'start'); + $borders[] = array('version' => $interval->getEnd()->getVersion(), 'operator' => $interval->getEnd()->getOperator(), 'side' => 'end'); + } + } + + $opSortOrder = self::$opSortOrder; + usort($borders, function ($a, $b) use ($opSortOrder) { + $order = version_compare($a['version'], $b['version']); + if ($order === 0) { + return $opSortOrder[$a['operator']] - $opSortOrder[$b['operator']]; + } + + return $order; + }); + + $activeIntervals = 0; + $intervals = array(); + $index = 0; + $activationThreshold = $constraint->isConjunctive() ? \count($numericGroups) : 1; + $start = null; + foreach ($borders as $border) { + if ($border['side'] === 'start') { + $activeIntervals++; + } else { + $activeIntervals--; + } + if (!$start && $activeIntervals >= $activationThreshold) { + $start = new Constraint($border['operator'], $border['version']); + } elseif ($start && $activeIntervals < $activationThreshold) { + // filter out invalid intervals like > x - <= x, or >= x - < x + if ( + version_compare($start->getVersion(), $border['version'], '=') + && ( + ($start->getOperator() === '>' && $border['operator'] === '<=') + || ($start->getOperator() === '>=' && $border['operator'] === '<') + ) + ) { + unset($intervals[$index]); + } else { + $intervals[$index] = new Interval($start, new Constraint($border['operator'], $border['version'])); + $index++; + + if ($stopOnFirstValidInterval) { + break; + } + } + + $start = null; + } + } + + return array('numeric' => $intervals, 'branches' => $branches); + } + + /** + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + private static function generateSingleConstraintIntervals(Constraint $constraint) + { + $op = $constraint->getOperator(); + + // handle branch constraints first + if (strpos($constraint->getVersion(), 'dev-') === 0) { + $intervals = array(); + $branches = array('names' => array(), 'exclude' => false); + + // != dev-foo means any numeric version may match, we treat >/< like != they are not really defined for branches + if ($op === '!=') { + $intervals[] = new Interval(Interval::fromZero(), Interval::untilPositiveInfinity()); + $branches = array('names' => array($constraint->getVersion()), 'exclude' => true); + } elseif ($op === '==') { + $branches['names'][] = $constraint->getVersion(); + } + + return array( + 'numeric' => $intervals, + 'branches' => $branches, + ); + } + + if ($op[0] === '>') { // > & >= + return array('numeric' => array(new Interval($constraint, Interval::untilPositiveInfinity())), 'branches' => Interval::noDev()); + } + if ($op[0] === '<') { // < & <= + return array('numeric' => array(new Interval(Interval::fromZero(), $constraint)), 'branches' => Interval::noDev()); + } + if ($op === '!=') { + // convert !=x to intervals of 0 - x - +inf + dev* + return array('numeric' => array( + new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())), + new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity()), + ), 'branches' => Interval::anyDev()); + } + + // convert ==x to an interval of >=x - <=x + return array('numeric' => array( + new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion())), + ), 'branches' => Interval::noDev()); + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/Semver.php b/trilhas_poo/vendor/composer/semver/src/Semver.php new file mode 100644 index 0000000..4fe9075 --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/Semver.php @@ -0,0 +1,129 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\Constraint; + +class Semver +{ + const SORT_ASC = 1; + const SORT_DESC = -1; + + /** @var VersionParser */ + private static $versionParser; + + /** + * Determine if given version satisfies given constraints. + * + * @param string $version + * @param string $constraints + * + * @return bool + */ + public static function satisfies($version, $constraints) + { + if (null === self::$versionParser) { + self::$versionParser = new VersionParser(); + } + + $versionParser = self::$versionParser; + $provider = new Constraint('==', $versionParser->normalize($version)); + $parsedConstraints = $versionParser->parseConstraints($constraints); + + return $parsedConstraints->matches($provider); + } + + /** + * Return all versions that satisfy given constraints. + * + * @param string[] $versions + * @param string $constraints + * + * @return list + */ + public static function satisfiedBy(array $versions, $constraints) + { + $versions = array_filter($versions, function ($version) use ($constraints) { + return Semver::satisfies($version, $constraints); + }); + + return array_values($versions); + } + + /** + * Sort given array of versions. + * + * @param string[] $versions + * + * @return list + */ + public static function sort(array $versions) + { + return self::usort($versions, self::SORT_ASC); + } + + /** + * Sort given array of versions in reverse. + * + * @param string[] $versions + * + * @return list + */ + public static function rsort(array $versions) + { + return self::usort($versions, self::SORT_DESC); + } + + /** + * @param string[] $versions + * @param int $direction + * + * @return list + */ + private static function usort(array $versions, $direction) + { + if (null === self::$versionParser) { + self::$versionParser = new VersionParser(); + } + + $versionParser = self::$versionParser; + $normalized = array(); + + // Normalize outside of usort() scope for minor performance increase. + // Creates an array of arrays: [[normalized, key], ...] + foreach ($versions as $key => $version) { + $normalizedVersion = $versionParser->normalize($version); + $normalizedVersion = $versionParser->normalizeDefaultBranch($normalizedVersion); + $normalized[] = array($normalizedVersion, $key); + } + + usort($normalized, function (array $left, array $right) use ($direction) { + if ($left[0] === $right[0]) { + return 0; + } + + if (Comparator::lessThan($left[0], $right[0])) { + return -$direction; + } + + return $direction; + }); + + // Recreate input array, using the original indexes which are now in sorted order. + $sorted = array(); + foreach ($normalized as $item) { + $sorted[] = $versions[$item[1]]; + } + + return $sorted; + } +} diff --git a/trilhas_poo/vendor/composer/semver/src/VersionParser.php b/trilhas_poo/vendor/composer/semver/src/VersionParser.php new file mode 100644 index 0000000..305a0fa --- /dev/null +++ b/trilhas_poo/vendor/composer/semver/src/VersionParser.php @@ -0,0 +1,591 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\Semver; + +use Composer\Semver\Constraint\ConstraintInterface; +use Composer\Semver\Constraint\MatchAllConstraint; +use Composer\Semver\Constraint\MultiConstraint; +use Composer\Semver\Constraint\Constraint; + +/** + * Version parser. + * + * @author Jordi Boggiano + */ +class VersionParser +{ + /** + * Regex to match pre-release data (sort of). + * + * Due to backwards compatibility: + * - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted. + * - Only stabilities as recognized by Composer are allowed to precede a numerical identifier. + * - Numerical-only pre-release identifiers are not supported, see tests. + * + * |--------------| + * [major].[minor].[patch] -[pre-release] +[build-metadata] + * + * @var string + */ + private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?'; + + /** @var string */ + private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev'; + + /** + * Returns the stability of a version. + * + * @param string $version + * + * @return string + * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' + */ + public static function parseStability($version) + { + $version = (string) preg_replace('{#.+$}', '', (string) $version); + + if (strpos($version, 'dev-') === 0 || '-dev' === substr($version, -4)) { + return 'dev'; + } + + preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match); + + if (!empty($match[3])) { + return 'dev'; + } + + if (!empty($match[1])) { + if ('beta' === $match[1] || 'b' === $match[1]) { + return 'beta'; + } + if ('alpha' === $match[1] || 'a' === $match[1]) { + return 'alpha'; + } + if ('rc' === $match[1]) { + return 'RC'; + } + } + + return 'stable'; + } + + /** + * @param string $stability + * + * @return string + * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' + */ + public static function normalizeStability($stability) + { + $stability = strtolower((string) $stability); + + if (!in_array($stability, array('stable', 'rc', 'beta', 'alpha', 'dev'), true)) { + throw new \InvalidArgumentException('Invalid stability string "'.$stability.'", expected one of stable, RC, beta, alpha or dev'); + } + + return $stability === 'rc' ? 'RC' : $stability; + } + + /** + * Normalizes a version string to be able to perform comparisons on it. + * + * @param string $version + * @param ?string $fullVersion optional complete version string to give more context + * + * @throws \UnexpectedValueException + * + * @return string + */ + public function normalize($version, $fullVersion = null) + { + $version = trim((string) $version); + $origVersion = $version; + if (null === $fullVersion) { + $fullVersion = $version; + } + + // strip off aliasing + if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) { + $version = $match[1]; + } + + // strip off stability flag + if (preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) { + $version = substr($version, 0, strlen($version) - strlen($match[0])); + } + + // normalize master/trunk/default branches to dev-name for BC with 1.x as these used to be valid constraints + if (\in_array($version, array('master', 'trunk', 'default'), true)) { + $version = 'dev-' . $version; + } + + // if requirement is branch-like, use full name + if (stripos($version, 'dev-') === 0) { + return 'dev-' . substr($version, 4); + } + + // strip off build metadata + if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) { + $version = $match[1]; + } + + // match classical versioning + if (preg_match('{^v?(\d{1,5}+)(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) { + $version = $matches[1] + . (!empty($matches[2]) ? $matches[2] : '.0') + . (!empty($matches[3]) ? $matches[3] : '.0') + . (!empty($matches[4]) ? $matches[4] : '.0'); + $index = 5; + // match date(time) based versioning + } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3}){0,2})' . self::$modifierRegex . '$}i', $version, $matches)) { + $version = (string) preg_replace('{\D}', '.', $matches[1]); + $index = 2; + } + + // add version modifiers if a version was matched + if (isset($index)) { + if (!empty($matches[$index])) { + if ('stable' === $matches[$index]) { + return $version; + } + $version .= '-' . $this->expandStability($matches[$index]) . (isset($matches[$index + 1]) && '' !== $matches[$index + 1] ? ltrim($matches[$index + 1], '.-') : ''); + } + + if (!empty($matches[$index + 2])) { + $version .= '-dev'; + } + + return $version; + } + + // match dev branches + if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) { + try { + $normalized = $this->normalizeBranch($match[1]); + // a branch ending with -dev is only valid if it is numeric + // if it gets prefixed with dev- it means the branch name should + // have had a dev- prefix already when passed to normalize + if (strpos($normalized, 'dev-') === false) { + return $normalized; + } + } catch (\Exception $e) { + } + } + + $extraMessage = ''; + if (preg_match('{ +as +' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))?$}', $fullVersion)) { + $extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version'; + } elseif (preg_match('{^' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))? +as +}', $fullVersion)) { + $extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-'; + } + + throw new \UnexpectedValueException('Invalid version string "' . $origVersion . '"' . $extraMessage); + } + + /** + * Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison. + * + * @param string $branch Branch name (e.g. 2.1.x-dev) + * + * @return string|false Numeric prefix if present (e.g. 2.1.) or false + */ + public function parseNumericAliasPrefix($branch) + { + if (preg_match('{^(?P(\d++\\.)*\d++)(?:\.x)?-dev$}i', (string) $branch, $matches)) { + return $matches['version'] . '.'; + } + + return false; + } + + /** + * Normalizes a branch name to be able to perform comparisons on it. + * + * @param string $name + * + * @return string + */ + public function normalizeBranch($name) + { + $name = trim((string) $name); + + if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) { + $version = ''; + for ($i = 1; $i < 5; ++$i) { + $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x'; + } + + return str_replace('x', '9999999', $version) . '-dev'; + } + + return 'dev-' . $name; + } + + /** + * Normalizes a default branch name (i.e. master on git) to 9999999-dev. + * + * @param string $name + * + * @return string + * + * @deprecated No need to use this anymore in theory, Composer 2 does not normalize any branch names to 9999999-dev anymore + */ + public function normalizeDefaultBranch($name) + { + if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') { + return '9999999-dev'; + } + + return (string) $name; + } + + /** + * Parses a constraint string into MultiConstraint and/or Constraint objects. + * + * @param string $constraints + * + * @return ConstraintInterface + */ + public function parseConstraints($constraints) + { + $prettyConstraint = (string) $constraints; + + $orConstraints = preg_split('{\s*\|\|?\s*}', trim((string) $constraints)); + if (false === $orConstraints) { + throw new \RuntimeException('Failed to preg_split string: '.$constraints); + } + $orGroups = array(); + + foreach ($orConstraints as $orConstraint) { + $andConstraints = preg_split('{(?< ,]) *(? 1) { + $constraintObjects = array(); + foreach ($andConstraints as $andConstraint) { + foreach ($this->parseConstraint($andConstraint) as $parsedAndConstraint) { + $constraintObjects[] = $parsedAndConstraint; + } + } + } else { + $constraintObjects = $this->parseConstraint($andConstraints[0]); + } + + if (1 === \count($constraintObjects)) { + $constraint = $constraintObjects[0]; + } else { + $constraint = new MultiConstraint($constraintObjects); + } + + $orGroups[] = $constraint; + } + + $parsedConstraint = MultiConstraint::create($orGroups, false); + + $parsedConstraint->setPrettyString($prettyConstraint); + + return $parsedConstraint; + } + + /** + * @param string $constraint + * + * @throws \UnexpectedValueException + * + * @return array + * + * @phpstan-return non-empty-array + */ + private function parseConstraint($constraint) + { + // strip off aliasing + if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $constraint, $match)) { + $constraint = $match[1]; + } + + // strip @stability flags, and keep it for later use + if (preg_match('{^([^,\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) { + $constraint = '' !== $match[1] ? $match[1] : '*'; + if ($match[2] !== 'stable') { + $stabilityModifier = $match[2]; + } + } + + // get rid of #refs as those are used by composer only + if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraint, $match)) { + $constraint = $match[1]; + } + + if (preg_match('{^(v)?[xX*](\.[xX*])*$}i', $constraint, $match)) { + if (!empty($match[1]) || !empty($match[2])) { + return array(new Constraint('>=', '0.0.0.0-dev')); + } + + return array(new MatchAllConstraint()); + } + + $versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?(?:' . self::$modifierRegex . '|\.([xX*][.-]?dev))(?:\+[^\s]+)?'; + + // Tilde Range + // + // Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous + // version, to ensure that unstable instances of the current version are allowed. However, if a stability + // suffix is added to the constraint, then a >= match on the current version is used instead. + if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) { + if (strpos($constraint, '~>') === 0) { + throw new \UnexpectedValueException( + 'Could not parse version constraint ' . $constraint . ': ' . + 'Invalid operator "~>", you probably meant to use the "~" operator' + ); + } + + // Work out which position in the version we are operating at + if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) { + $position = 4; + } elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { + $position = 3; + } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { + $position = 2; + } else { + $position = 1; + } + + // when matching 2.x-dev or 3.0.x-dev we have to shift the second or third number, despite no second/third number matching above + if (!empty($matches[8])) { + $position++; + } + + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + + $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highPosition = max(1, $position - 1); + $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + + return array( + $lowerBound, + $upperBound, + ); + } + + // Caret Range + // + // Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. + // In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for + // versions 0.X >=0.1.0, and no updates for versions 0.0.X + if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) { + // Work out which position in the version we are operating at + if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) { + $position = 1; + } elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) { + $position = 2; + } else { + $position = 3; + } + + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + + $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + + return array( + $lowerBound, + $upperBound, + ); + } + + // X Range + // + // Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple. + // A partial version range is treated as an X-Range, so the special character is in fact optional. + if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) { + if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) { + $position = 3; + } elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) { + $position = 2; + } else { + $position = 1; + } + + $lowVersion = $this->manipulateVersionString($matches, $position) . '-dev'; + $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; + + if ($lowVersion === '0.0.0.0-dev') { + return array(new Constraint('<', $highVersion)); + } + + return array( + new Constraint('>=', $lowVersion), + new Constraint('<', $highVersion), + ); + } + + // Hyphen Range + // + // Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range, + // then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in + // the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but + // nothing that would be greater than the provided tuple parts. + if (preg_match('{^(?P' . $versionRegex . ') +- +(?P' . $versionRegex . ')($)}i', $constraint, $matches)) { + // Calculate the stability suffix + $lowStabilitySuffix = ''; + if (empty($matches[6]) && empty($matches[8]) && empty($matches[9])) { + $lowStabilitySuffix = '-dev'; + } + + $lowVersion = $this->normalize($matches['from']); + $lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix); + + $empty = function ($x) { + return ($x === 0 || $x === '0') ? false : empty($x); + }; + + if ((!$empty($matches[12]) && !$empty($matches[13])) || !empty($matches[15]) || !empty($matches[17]) || !empty($matches[18])) { + $highVersion = $this->normalize($matches['to']); + $upperBound = new Constraint('<=', $highVersion); + } else { + $highMatch = array('', $matches[11], $matches[12], $matches[13], $matches[14]); + + // validate to version + $this->normalize($matches['to']); + + $highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + } + + return array( + $lowerBound, + $upperBound, + ); + } + + // Basic Comparators + if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) { + try { + try { + $version = $this->normalize($matches[2]); + } catch (\UnexpectedValueException $e) { + // recover from an invalid constraint like foobar-dev which should be dev-foobar + // except if the constraint uses a known operator, in which case it must be a parse error + if (substr($matches[2], -4) === '-dev' && preg_match('{^[0-9a-zA-Z-./]+$}', $matches[2])) { + $version = $this->normalize('dev-'.substr($matches[2], 0, -4)); + } else { + throw $e; + } + } + + $op = $matches[1] ?: '='; + + if ($op !== '==' && $op !== '=' && !empty($stabilityModifier) && self::parseStability($version) === 'stable') { + $version .= '-' . $stabilityModifier; + } elseif ('<' === $op || '>=' === $op) { + if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) { + if (strpos($matches[2], 'dev-') !== 0) { + $version .= '-dev'; + } + } + } + + return array(new Constraint($matches[1] ?: '=', $version)); + } catch (\Exception $e) { + } + } + + $message = 'Could not parse version constraint ' . $constraint; + if (isset($e)) { + $message .= ': ' . $e->getMessage(); + } + + throw new \UnexpectedValueException($message); + } + + /** + * Increment, decrement, or simply pad a version number. + * + * Support function for {@link parseConstraint()} + * + * @param array $matches Array with version parts in array indexes 1,2,3,4 + * @param int $position 1,2,3,4 - which segment of the version to increment/decrement + * @param int $increment + * @param string $pad The string to pad version parts after $position + * + * @return string|null The new version + * + * @phpstan-param string[] $matches + */ + private function manipulateVersionString(array $matches, $position, $increment = 0, $pad = '0') + { + for ($i = 4; $i > 0; --$i) { + if ($i > $position) { + $matches[$i] = $pad; + } elseif ($i === $position && $increment) { + $matches[$i] += $increment; + // If $matches[$i] was 0, carry the decrement + if ($matches[$i] < 0) { + $matches[$i] = $pad; + --$position; + + // Return null on a carry overflow + if ($i === 1) { + return null; + } + } + } + } + + return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4]; + } + + /** + * Expand shorthand stability string to long version. + * + * @param string $stability + * + * @return string + */ + private function expandStability($stability) + { + $stability = strtolower($stability); + + switch ($stability) { + case 'a': + return 'alpha'; + case 'b': + return 'beta'; + case 'p': + case 'pl': + return 'patch'; + case 'rc': + return 'RC'; + default: + return $stability; + } + } +} diff --git a/trilhas_poo/vendor/composer/xdebug-handler/CHANGELOG.md b/trilhas_poo/vendor/composer/xdebug-handler/CHANGELOG.md new file mode 100644 index 0000000..62ebe22 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/CHANGELOG.md @@ -0,0 +1,143 @@ +## [Unreleased] + +## [3.0.5] - 2024-05-06 + * Fixed: fail restart if PHP_BINARY is not available + +## [3.0.4] - 2024-03-26 + * Added: Functional tests. + * Fixed: Incompatibility with PHPUnit 10. + +## [3.0.3] - 2022-02-25 + * Added: support for composer/pcre versions 2 and 3. + +## [3.0.2] - 2022-02-24 + * Fixed: regression in 3.0.1 affecting Xdebug 2 + +## [3.0.1] - 2022-01-04 + * Fixed: error when calling `isXdebugActive` before class instantiation. + +## [3.0.0] - 2021-12-23 + * Removed: support for legacy PHP versions (< PHP 7.2.5). + * Added: type declarations to arguments and return values. + * Added: strict typing to all classes. + +## [2.0.3] - 2021-12-08 + * Added: support, type annotations and refactoring for stricter PHPStan analysis. + +## [2.0.2] - 2021-07-31 + * Added: support for `xdebug_info('mode')` in Xdebug 3.1. + * Added: support for Psr\Log versions 2 and 3. + * Fixed: remove ini directives from non-cli HOST/PATH sections. + +## [2.0.1] - 2021-05-05 + * Fixed: don't restart if the cwd is a UNC path and cmd.exe will be invoked. + +## [2.0.0] - 2021-04-09 + * Break: this is a major release, see [UPGRADE.md](UPGRADE.md) for more information. + * Break: removed optional `$colorOption` constructor param and passthru fallback. + * Break: renamed `requiresRestart` param from `$isLoaded` to `$default`. + * Break: changed `restart` param `$command` from a string to an array. + * Added: support for Xdebug3 to only restart if Xdebug is not running with `xdebug.mode=off`. + * Added: `isXdebugActive()` method to determine if Xdebug is still running in the restart. + * Added: feature to bypass the shell in PHP-7.4+ by giving `proc_open` an array of arguments. + * Added: Process utility class to the API. + +## [1.4.6] - 2021-03-25 + * Fixed: fail restart if `proc_open` has been disabled in `disable_functions`. + * Fixed: enable Windows CTRL event handling in the restarted process. + +## [1.4.5] - 2020-11-13 + * Fixed: use `proc_open` when available for correct FD forwarding to the restarted process. + +## [1.4.4] - 2020-10-24 + * Fixed: exception if 'pcntl_signal' is disabled. + +## [1.4.3] - 2020-08-19 + * Fixed: restore SIGINT to default handler in restarted process if no other handler exists. + +## [1.4.2] - 2020-06-04 + * Fixed: ignore SIGINTs to let the restarted process handle them. + +## [1.4.1] - 2020-03-01 + * Fixed: restart fails if an ini file is empty. + +## [1.4.0] - 2019-11-06 + * Added: support for `NO_COLOR` environment variable: https://no-color.org + * Added: color support for Hyper terminal: https://github.com/zeit/hyper + * Fixed: correct capitalization of Xdebug (apparently). + * Fixed: improved handling for uopz extension. + +## [1.3.3] - 2019-05-27 + * Fixed: add environment changes to `$_ENV` if it is being used. + +## [1.3.2] - 2019-01-28 + * Fixed: exit call being blocked by uopz extension, resulting in application code running twice. + +## [1.3.1] - 2018-11-29 + * Fixed: fail restart if `passthru` has been disabled in `disable_functions`. + * Fixed: fail restart if an ini file cannot be opened, otherwise settings will be missing. + +## [1.3.0] - 2018-08-31 + * Added: `setPersistent` method to use environment variables for the restart. + * Fixed: improved debugging by writing output to stderr. + * Fixed: no restart when `php_ini_scanned_files` is not functional and is needed. + +## [1.2.1] - 2018-08-23 + * Fixed: fatal error with apc, when using `apc.mmap_file_mask`. + +## [1.2.0] - 2018-08-16 + * Added: debug information using `XDEBUG_HANDLER_DEBUG`. + * Added: fluent interface for setters. + * Added: `PhpConfig` helper class for calling PHP sub-processes. + * Added: `PHPRC` original value to restart stettings, for use in a restarted process. + * Changed: internal procedure to disable ini-scanning, using `-n` command-line option. + * Fixed: replaced `escapeshellarg` usage to avoid locale problems. + * Fixed: improved color-option handling to respect double-dash delimiter. + * Fixed: color-option handling regression from main script changes. + * Fixed: improved handling when checking main script. + * Fixed: handling for standard input, that never actually did anything. + * Fixed: fatal error when ctype extension is not available. + +## [1.1.0] - 2018-04-11 + * Added: `getRestartSettings` method for calling PHP processes in a restarted process. + * Added: API definition and @internal class annotations. + * Added: protected `requiresRestart` method for extending classes. + * Added: `setMainScript` method for applications that change the working directory. + * Changed: private `tmpIni` variable to protected for extending classes. + * Fixed: environment variables not available in $_SERVER when restored in the restart. + * Fixed: relative path problems caused by Phar::interceptFileFuncs. + * Fixed: incorrect handling when script file cannot be found. + +## [1.0.0] - 2018-03-08 + * Added: PSR3 logging for optional status output. + * Added: existing ini settings are merged to catch command-line overrides. + * Added: code, tests and other artefacts to decouple from Composer. + * Break: the following class was renamed: + - `Composer\XdebugHandler` -> `Composer\XdebugHandler\XdebugHandler` + +[Unreleased]: https://github.com/composer/xdebug-handler/compare/3.0.5...HEAD +[3.0.5]: https://github.com/composer/xdebug-handler/compare/3.0.4...3.0.5 +[3.0.4]: https://github.com/composer/xdebug-handler/compare/3.0.3...3.0.4 +[3.0.3]: https://github.com/composer/xdebug-handler/compare/3.0.2...3.0.3 +[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/composer/xdebug-handler/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/xdebug-handler/compare/2.0.3...3.0.0 +[2.0.3]: https://github.com/composer/xdebug-handler/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/composer/xdebug-handler/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/composer/xdebug-handler/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/composer/xdebug-handler/compare/1.4.6...2.0.0 +[1.4.6]: https://github.com/composer/xdebug-handler/compare/1.4.5...1.4.6 +[1.4.5]: https://github.com/composer/xdebug-handler/compare/1.4.4...1.4.5 +[1.4.4]: https://github.com/composer/xdebug-handler/compare/1.4.3...1.4.4 +[1.4.3]: https://github.com/composer/xdebug-handler/compare/1.4.2...1.4.3 +[1.4.2]: https://github.com/composer/xdebug-handler/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/xdebug-handler/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/xdebug-handler/compare/1.3.3...1.4.0 +[1.3.3]: https://github.com/composer/xdebug-handler/compare/1.3.2...1.3.3 +[1.3.2]: https://github.com/composer/xdebug-handler/compare/1.3.1...1.3.2 +[1.3.1]: https://github.com/composer/xdebug-handler/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/composer/xdebug-handler/compare/1.2.1...1.3.0 +[1.2.1]: https://github.com/composer/xdebug-handler/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/composer/xdebug-handler/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/xdebug-handler/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/xdebug-handler/compare/d66f0d15cb57...1.0.0 diff --git a/trilhas_poo/vendor/composer/xdebug-handler/LICENSE b/trilhas_poo/vendor/composer/xdebug-handler/LICENSE new file mode 100644 index 0000000..963618a --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Composer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/trilhas_poo/vendor/composer/xdebug-handler/README.md b/trilhas_poo/vendor/composer/xdebug-handler/README.md new file mode 100644 index 0000000..f7f581a --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/README.md @@ -0,0 +1,305 @@ +# composer/xdebug-handler + +[![packagist](https://img.shields.io/packagist/v/composer/xdebug-handler)](https://packagist.org/packages/composer/xdebug-handler) +[![Continuous Integration](https://github.com/composer/xdebug-handler/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/xdebug-handler/actions?query=branch:main) +![license](https://img.shields.io/github/license/composer/xdebug-handler.svg) +![php](https://img.shields.io/packagist/php-v/composer/xdebug-handler?colorB=8892BF) + +Restart a CLI process without loading the Xdebug extension, unless `xdebug.mode=off`. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +### Version 3 + +Removed support for legacy PHP versions and added type declarations. + +Long term support for version 2 (PHP 5.3.2 - 7.2.4) follows [Composer 2.2 LTS](https://blog.packagist.com/composer-2-2/) policy. + +## Installation + +Install the latest version with: + +```bash +$ composer require composer/xdebug-handler +``` + +## Requirements + +* PHP 7.2.5 minimum, although using the latest PHP version is highly recommended. + +## Basic Usage +```php +use Composer\XdebugHandler\XdebugHandler; + +$xdebug = new XdebugHandler('myapp'); +$xdebug->check(); +unset($xdebug); +``` + +The constructor takes a single parameter, `$envPrefix`, which is upper-cased and prepended to default base values to create two distinct environment variables. The above example enables the use of: + +- `MYAPP_ALLOW_XDEBUG=1` to override automatic restart and allow Xdebug +- `MYAPP_ORIGINAL_INIS` to obtain ini file locations in a restarted process + +## Advanced Usage + +* [How it works](#how-it-works) +* [Limitations](#limitations) +* [Helper methods](#helper-methods) +* [Setter methods](#setter-methods) +* [Process configuration](#process-configuration) +* [Troubleshooting](#troubleshooting) +* [Extending the library](#extending-the-library) +* [Examples](#examples) + +### How it works + +A temporary ini file is created from the loaded (and scanned) ini files, with any references to the Xdebug extension commented out. Current ini settings are merged, so that most ini settings made on the command-line or by the application are included (see [Limitations](#limitations)) + +* `MYAPP_ALLOW_XDEBUG` is set with internal data to flag and use in the restart. +* The command-line and environment are [configured](#process-configuration) for the restart. +* The application is restarted in a new process. + * The restart settings are stored in the environment. + * `MYAPP_ALLOW_XDEBUG` is unset. + * The application runs and exits. +* The main process exits with the exit code from the restarted process. + +See [Examples](#examples) for further information. + +#### Signal handling +Asynchronous signal handling is automatically enabled if the pcntl extension is loaded. `SIGINT` is set to `SIG_IGN` in the parent +process and restored to `SIG_DFL` in the restarted process (if no other handler has been set). + +From PHP 7.4 on Windows, `CTRL+C` and `CTRL+BREAK` handling is automatically enabled in the restarted process and ignored in the parent process. + +### Limitations +There are a few things to be aware of when running inside a restarted process. + +* Extensions set on the command-line will not be loaded. +* Ini file locations will be reported as per the restart - see [getAllIniFiles()](#getallinifiles-array). +* Php sub-processes may be loaded with Xdebug enabled - see [Process configuration](#process-configuration). + +### Helper methods +These static methods provide information from the current process, regardless of whether it has been restarted or not. + +#### _getAllIniFiles(): array_ +Returns an array of the original ini file locations. Use this instead of calling `php_ini_loaded_file` and `php_ini_scanned_files`, which will report the wrong values in a restarted process. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$files = XdebugHandler::getAllIniFiles(); + +# $files[0] always exists, it could be an empty string +$loadedIni = array_shift($files); +$scannedInis = $files; +``` + +These locations are also available in the `MYAPP_ORIGINAL_INIS` environment variable. This is a path-separated string comprising the location returned from `php_ini_loaded_file`, which could be empty, followed by locations parsed from calling `php_ini_scanned_files`. + +#### _getRestartSettings(): ?array_ +Returns an array of settings that can be used with PHP [sub-processes](#sub-processes), or null if the process was not restarted. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$settings = XdebugHandler::getRestartSettings(); +/** + * $settings: array (if the current process was restarted, + * or called with the settings from a previous restart), or null + * + * 'tmpIni' => the temporary ini file used in the restart (string) + * 'scannedInis' => if there were any scanned inis (bool) + * 'scanDir' => the original PHP_INI_SCAN_DIR value (false|string) + * 'phprc' => the original PHPRC value (false|string) + * 'inis' => the original inis from getAllIniFiles (array) + * 'skipped' => the skipped version from getSkippedVersion (string) + */ +``` + +#### _getSkippedVersion(): string_ +Returns the Xdebug version string that was skipped by the restart, or an empty string if there was no restart (or Xdebug is still loaded, perhaps by an extending class restarting for a reason other than removing Xdebug). + +```php +use Composer\XdebugHandler\XdebugHandler; + +$version = XdebugHandler::getSkippedVersion(); +# $version: '3.1.1' (for example), or an empty string +``` + +#### _isXdebugActive(): bool_ +Returns true if Xdebug is loaded and is running in an active mode (if it supports modes). Returns false if Xdebug is not loaded, or it is running with `xdebug.mode=off`. + +### Setter methods +These methods implement a fluent interface and must be called before the main `check()` method. + +#### _setLogger(LoggerInterface $logger): self_ +Enables the output of status messages to an external PSR3 logger. All messages are reported with either `DEBUG` or `WARNING` log levels. For example (showing the level and message): + +``` +// No restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=off +DEBUG No restart (APP_ALLOW_XDEBUG=0) Allowed by xdebug.mode + +// Restart overridden +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=coverage,debug,develop +DEBUG No restart (MYAPP_ALLOW_XDEBUG=1) + +// Failed restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.0) +WARNING No restart (Unable to create temp ini file at: ...) +``` + +Status messages can also be output with `XDEBUG_HANDLER_DEBUG`. See [Troubleshooting](#troubleshooting). + +#### _setMainScript(string $script): self_ +Sets the location of the main script to run in the restart. This is only needed in more esoteric use-cases, or if the `argv[0]` location is inaccessible. The script name `--` is supported for standard input. + +#### _setPersistent(): self_ +Configures the restart using [persistent settings](#persistent-settings), so that Xdebug is not loaded in any sub-process. + +Use this method if your application invokes one or more PHP sub-process and the Xdebug extension is not needed. This avoids the overhead of implementing specific [sub-process](#sub-processes) strategies. + +Alternatively, this method can be used to set up a default _Xdebug-free_ environment which can be changed if a sub-process requires Xdebug, then restored afterwards: + +```php +function SubProcessWithXdebug() +{ + $phpConfig = new Composer\XdebugHandler\PhpConfig(); + + # Set the environment to the original configuration + $phpConfig->useOriginal(); + + # run the process with Xdebug loaded + ... + + # Restore Xdebug-free environment + $phpConfig->usePersistent(); +} +``` + +### Process configuration +The library offers two strategies to invoke a new PHP process without loading Xdebug, using either _standard_ or _persistent_ settings. Note that this is only important if the application calls a PHP sub-process. + +#### Standard settings +Uses command-line options to remove Xdebug from the new process only. + +* The -n option is added to the command-line. This tells PHP not to scan for additional inis. +* The temporary ini is added to the command-line with the -c option. + +>_If the new process calls a PHP sub-process, Xdebug will be loaded in that sub-process (unless it implements xdebug-handler, in which case there will be another restart)._ + +This is the default strategy used in the restart. + +#### Persistent settings +Uses environment variables to remove Xdebug from the new process and persist these settings to any sub-process. + +* `PHP_INI_SCAN_DIR` is set to an empty string. This tells PHP not to scan for additional inis. +* `PHPRC` is set to the temporary ini. + +>_If the new process calls a PHP sub-process, Xdebug will not be loaded in that sub-process._ + +This strategy can be used in the restart by calling [setPersistent()](#setpersistent-self). + +#### Sub-processes +The `PhpConfig` helper class makes it easy to invoke a PHP sub-process (with or without Xdebug loaded), regardless of whether there has been a restart. + +Each of its methods returns an array of PHP options (to add to the command-line) and sets up the environment for the required strategy. The [getRestartSettings()](#getrestartsettings-array) method is used internally. + +* `useOriginal()` - Xdebug will be loaded in the new process. +* `useStandard()` - Xdebug will **not** be loaded in the new process - see [standard settings](#standard-settings). +* `userPersistent()` - Xdebug will **not** be loaded in the new process - see [persistent settings](#persistent-settings) + +If there was no restart, an empty options array is returned and the environment is not changed. + +```php +use Composer\XdebugHandler\PhpConfig; + +$config = new PhpConfig; + +$options = $config->useOriginal(); +# $options: empty array +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->useStandard(); +# $options: [-n, -c, tmpIni] +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->usePersistent(); +# $options: empty array +# environment: PHPRC=tmpIni, PHP_INI_SCAN_DIR='' +``` + +### Troubleshooting +The following environment settings can be used to troubleshoot unexpected behavior: + +* `XDEBUG_HANDLER_DEBUG=1` Outputs status messages to `STDERR`, if it is defined, irrespective of any PSR3 logger. Each message is prefixed `xdebug-handler[pid]`, where pid is the process identifier. + +* `XDEBUG_HANDLER_DEBUG=2` As above, but additionally saves the temporary ini file and reports its location in a status message. + +### Extending the library +The API is defined by classes and their accessible elements that are not annotated as @internal. The main class has two protected methods that can be overridden to provide additional functionality: + +#### _requiresRestart(bool $default): bool_ +By default the process will restart if Xdebug is loaded and not running with `xdebug.mode=off`. Extending this method allows an application to decide, by returning a boolean (or equivalent) value. +It is only called if `MYAPP_ALLOW_XDEBUG` is empty, so it will not be called in the restarted process (where this variable contains internal data), or if the restart has been overridden. + +Note that the [setMainScript()](#setmainscriptstring-script-self) and [setPersistent()](#setpersistent-self) setters can be used here, if required. + +#### _restart(array $command): void_ +An application can extend this to modify the temporary ini file, its location given in the `tmpIni` property. New settings can be safely appended to the end of the data, which is `PHP_EOL` terminated. + +The `$command` parameter is an array of unescaped command-line arguments that will be used for the new process. + +Remember to finish with `parent::restart($command)`. + +#### Example +This example demonstrates two ways to extend basic functionality: + +* To avoid the overhead of spinning up a new process, the restart is skipped if a simple help command is requested. + +* The application needs write-access to phar files, so it will force a restart if `phar.readonly` is set (regardless of whether Xdebug is loaded) and change this value in the temporary ini file. + +```php +use Composer\XdebugHandler\XdebugHandler; +use MyApp\Command; + +class MyRestarter extends XdebugHandler +{ + private $required; + + protected function requiresRestart(bool $default): bool + { + if (Command::isHelp()) { + # No need to disable Xdebug for this + return false; + } + + $this->required = (bool) ini_get('phar.readonly'); + return $this->required || $default; + } + + protected function restart(array $command): void + { + if ($this->required) { + # Add required ini setting to tmpIni + $content = file_get_contents($this->tmpIni); + $content .= 'phar.readonly=0'.PHP_EOL; + file_put_contents($this->tmpIni, $content); + } + + parent::restart($command); + } +} +``` + +### Examples +The `tests\App` directory contains command-line scripts that demonstrate the internal workings in a variety of scenarios. +See [Functional Test Scripts](./tests/App/README.md). + +## License +composer/xdebug-handler is licensed under the MIT License, see the LICENSE file for details. diff --git a/trilhas_poo/vendor/composer/xdebug-handler/composer.json b/trilhas_poo/vendor/composer/xdebug-handler/composer.json new file mode 100644 index 0000000..d205dc1 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/composer.json @@ -0,0 +1,44 @@ +{ + "name": "composer/xdebug-handler", + "description": "Restarts a process without Xdebug.", + "type": "library", + "license": "MIT", + "keywords": [ + "xdebug", + "performance" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/xdebug-handler/issues" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/log": "^1 || ^2 || ^3", + "composer/pcre": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan/phpstan": "^1.0", + "phpstan/phpstan-strict-rules": "^1.1", + "phpunit/phpunit": "^8.5 || ^9.6 || ^10.5" + }, + "autoload": { + "psr-4": { + "Composer\\XdebugHandler\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Composer\\XdebugHandler\\Tests\\": "tests" + } + }, + "scripts": { + "test": "@php vendor/bin/phpunit", + "phpstan": "@php vendor/bin/phpstan analyse" + } +} diff --git a/trilhas_poo/vendor/composer/xdebug-handler/src/PhpConfig.php b/trilhas_poo/vendor/composer/xdebug-handler/src/PhpConfig.php new file mode 100644 index 0000000..7edac88 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/src/PhpConfig.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace Composer\XdebugHandler; + +/** + * @author John Stevenson + * + * @phpstan-type restartData array{tmpIni: string, scannedInis: bool, scanDir: false|string, phprc: false|string, inis: string[], skipped: string} + */ +class PhpConfig +{ + /** + * Use the original PHP configuration + * + * @return string[] Empty array of PHP cli options + */ + public function useOriginal(): array + { + $this->getDataAndReset(); + return []; + } + + /** + * Use standard restart settings + * + * @return string[] PHP cli options + */ + public function useStandard(): array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + return ['-n', '-c', $data['tmpIni']]; + } + + return []; + } + + /** + * Use environment variables to persist settings + * + * @return string[] Empty array of PHP cli options + */ + public function usePersistent(): array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['tmpIni']); + $this->updateEnv('PHP_INI_SCAN_DIR', ''); + } + + return []; + } + + /** + * Returns restart data if available and resets the environment + * + * @phpstan-return restartData|null + */ + private function getDataAndReset(): ?array + { + $data = XdebugHandler::getRestartSettings(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['phprc']); + $this->updateEnv('PHP_INI_SCAN_DIR', $data['scanDir']); + } + + return $data; + } + + /** + * Updates a restart settings value in the environment + * + * @param string $name + * @param string|false $value + */ + private function updateEnv(string $name, $value): void + { + Process::setEnv($name, false !== $value ? $value : null); + } +} diff --git a/trilhas_poo/vendor/composer/xdebug-handler/src/Process.php b/trilhas_poo/vendor/composer/xdebug-handler/src/Process.php new file mode 100644 index 0000000..4e9f076 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/src/Process.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Composer\Pcre\Preg; + +/** + * Process utility functions + * + * @author John Stevenson + */ +class Process +{ + /** + * Escapes a string to be used as a shell argument. + * + * From https://github.com/johnstevenson/winbox-args + * MIT Licensed (c) John Stevenson + * + * @param string $arg The argument to be escaped + * @param bool $meta Additionally escape cmd.exe meta characters + * @param bool $module The argument is the module to invoke + */ + public static function escape(string $arg, bool $meta = true, bool $module = false): string + { + if (!defined('PHP_WINDOWS_VERSION_BUILD')) { + return "'".str_replace("'", "'\\''", $arg)."'"; + } + + $quote = strpbrk($arg, " \t") !== false || $arg === ''; + + $arg = Preg::replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes); + $dquotes = (bool) $dquotes; + + if ($meta) { + $meta = $dquotes || Preg::isMatch('/%[^%]+%/', $arg); + + if (!$meta) { + $quote = $quote || strpbrk($arg, '^&|<>()') !== false; + } elseif ($module && !$dquotes && $quote) { + $meta = false; + } + } + + if ($quote) { + $arg = '"'.(Preg::replace('/(\\\\*)$/', '$1$1', $arg)).'"'; + } + + if ($meta) { + $arg = Preg::replace('/(["^&|<>()%])/', '^$1', $arg); + } + + return $arg; + } + + /** + * Escapes an array of arguments that make up a shell command + * + * @param string[] $args Argument list, with the module name first + */ + public static function escapeShellCommand(array $args): string + { + $command = ''; + $module = array_shift($args); + + if ($module !== null) { + $command = self::escape($module, true, true); + + foreach ($args as $arg) { + $command .= ' '.self::escape($arg); + } + } + + return $command; + } + + /** + * Makes putenv environment changes available in $_SERVER and $_ENV + * + * @param string $name + * @param ?string $value A null value unsets the variable + */ + public static function setEnv(string $name, ?string $value = null): bool + { + $unset = null === $value; + + if (!putenv($unset ? $name : $name.'='.$value)) { + return false; + } + + if ($unset) { + unset($_SERVER[$name]); + } else { + $_SERVER[$name] = $value; + } + + // Update $_ENV if it is being used + if (false !== stripos((string) ini_get('variables_order'), 'E')) { + if ($unset) { + unset($_ENV[$name]); + } else { + $_ENV[$name] = $value; + } + } + + return true; + } +} diff --git a/trilhas_poo/vendor/composer/xdebug-handler/src/Status.php b/trilhas_poo/vendor/composer/xdebug-handler/src/Status.php new file mode 100644 index 0000000..96c5944 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/src/Status.php @@ -0,0 +1,222 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; + +/** + * @author John Stevenson + * @internal + */ +class Status +{ + const ENV_RESTART = 'XDEBUG_HANDLER_RESTART'; + const CHECK = 'Check'; + const ERROR = 'Error'; + const INFO = 'Info'; + const NORESTART = 'NoRestart'; + const RESTART = 'Restart'; + const RESTARTING = 'Restarting'; + const RESTARTED = 'Restarted'; + + /** @var bool */ + private $debug; + + /** @var string */ + private $envAllowXdebug; + + /** @var string|null */ + private $loaded; + + /** @var LoggerInterface|null */ + private $logger; + + /** @var bool */ + private $modeOff; + + /** @var float */ + private $time; + + /** + * @param string $envAllowXdebug Prefixed _ALLOW_XDEBUG name + * @param bool $debug Whether debug output is required + */ + public function __construct(string $envAllowXdebug, bool $debug) + { + $start = getenv(self::ENV_RESTART); + Process::setEnv(self::ENV_RESTART); + $this->time = is_numeric($start) ? round((microtime(true) - $start) * 1000) : 0; + + $this->envAllowXdebug = $envAllowXdebug; + $this->debug = $debug && defined('STDERR'); + $this->modeOff = false; + } + + /** + * Activates status message output to a PSR3 logger + * + * @return void + */ + public function setLogger(LoggerInterface $logger): void + { + $this->logger = $logger; + } + + /** + * Calls a handler method to report a message + * + * @throws \InvalidArgumentException If $op is not known + */ + public function report(string $op, ?string $data): void + { + if ($this->logger !== null || $this->debug) { + $param = (string) $data; + + switch($op) { + case self::CHECK: + $this->reportCheck($param); + break; + case self::ERROR: + $this->reportError($param); + break; + case self::INFO: + $this->reportInfo($param); + break; + case self::NORESTART: + $this->reportNoRestart(); + break; + case self::RESTART: + $this->reportRestart(); + break; + case self::RESTARTED: + $this->reportRestarted(); + break; + case self::RESTARTING: + $this->reportRestarting($param); + break; + default: + throw new \InvalidArgumentException('Unknown op handler: '.$op); + } + } + } + + /** + * Outputs a status message + */ + private function output(string $text, ?string $level = null): void + { + if ($this->logger !== null) { + $this->logger->log($level !== null ? $level: LogLevel::DEBUG, $text); + } + + if ($this->debug) { + fwrite(STDERR, sprintf('xdebug-handler[%d] %s', getmypid(), $text.PHP_EOL)); + } + } + + /** + * Checking status message + */ + private function reportCheck(string $loaded): void + { + list($version, $mode) = explode('|', $loaded); + + if ($version !== '') { + $this->loaded = '('.$version.')'.($mode !== '' ? ' xdebug.mode='.$mode : ''); + } + $this->modeOff = $mode === 'off'; + $this->output('Checking '.$this->envAllowXdebug); + } + + /** + * Error status message + */ + private function reportError(string $error): void + { + $this->output(sprintf('No restart (%s)', $error), LogLevel::WARNING); + } + + /** + * Info status message + */ + private function reportInfo(string $info): void + { + $this->output($info); + } + + /** + * No restart status message + */ + private function reportNoRestart(): void + { + $this->output($this->getLoadedMessage()); + + if ($this->loaded !== null) { + $text = sprintf('No restart (%s)', $this->getEnvAllow()); + if (!((bool) getenv($this->envAllowXdebug))) { + $text .= ' Allowed by '.($this->modeOff ? 'xdebug.mode' : 'application'); + } + $this->output($text); + } + } + + /** + * Restart status message + */ + private function reportRestart(): void + { + $this->output($this->getLoadedMessage()); + Process::setEnv(self::ENV_RESTART, (string) microtime(true)); + } + + /** + * Restarted status message + */ + private function reportRestarted(): void + { + $loaded = $this->getLoadedMessage(); + $text = sprintf('Restarted (%d ms). %s', $this->time, $loaded); + $level = $this->loaded !== null ? LogLevel::WARNING : null; + $this->output($text, $level); + } + + /** + * Restarting status message + */ + private function reportRestarting(string $command): void + { + $text = sprintf('Process restarting (%s)', $this->getEnvAllow()); + $this->output($text); + $text = 'Running: '.$command; + $this->output($text); + } + + /** + * Returns the _ALLOW_XDEBUG environment variable as name=value + */ + private function getEnvAllow(): string + { + return $this->envAllowXdebug.'='.getenv($this->envAllowXdebug); + } + + /** + * Returns the Xdebug status and version + */ + private function getLoadedMessage(): string + { + $loaded = $this->loaded !== null ? sprintf('loaded %s', $this->loaded) : 'not loaded'; + return 'The Xdebug extension is '.$loaded; + } +} diff --git a/trilhas_poo/vendor/composer/xdebug-handler/src/XdebugHandler.php b/trilhas_poo/vendor/composer/xdebug-handler/src/XdebugHandler.php new file mode 100644 index 0000000..a665939 --- /dev/null +++ b/trilhas_poo/vendor/composer/xdebug-handler/src/XdebugHandler.php @@ -0,0 +1,722 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Composer\XdebugHandler; + +use Composer\Pcre\Preg; +use Psr\Log\LoggerInterface; + +/** + * @author John Stevenson + * + * @phpstan-import-type restartData from PhpConfig + */ +class XdebugHandler +{ + const SUFFIX_ALLOW = '_ALLOW_XDEBUG'; + const SUFFIX_INIS = '_ORIGINAL_INIS'; + const RESTART_ID = 'internal'; + const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS'; + const DEBUG = 'XDEBUG_HANDLER_DEBUG'; + + /** @var string|null */ + protected $tmpIni; + + /** @var bool */ + private static $inRestart; + + /** @var string */ + private static $name; + + /** @var string|null */ + private static $skipped; + + /** @var bool */ + private static $xdebugActive; + + /** @var string|null */ + private static $xdebugMode; + + /** @var string|null */ + private static $xdebugVersion; + + /** @var bool */ + private $cli; + + /** @var string|null */ + private $debug; + + /** @var string */ + private $envAllowXdebug; + + /** @var string */ + private $envOriginalInis; + + /** @var bool */ + private $persistent; + + /** @var string|null */ + private $script; + + /** @var Status */ + private $statusWriter; + + /** + * Constructor + * + * The $envPrefix is used to create distinct environment variables. It is + * uppercased and prepended to the default base values. For example 'myapp' + * would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS. + * + * @param string $envPrefix Value used in environment variables + * @throws \RuntimeException If the parameter is invalid + */ + public function __construct(string $envPrefix) + { + if ($envPrefix === '') { + throw new \RuntimeException('Invalid constructor parameter'); + } + + self::$name = strtoupper($envPrefix); + $this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW; + $this->envOriginalInis = self::$name.self::SUFFIX_INIS; + + self::setXdebugDetails(); + self::$inRestart = false; + + if ($this->cli = PHP_SAPI === 'cli') { + $this->debug = (string) getenv(self::DEBUG); + } + + $this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug); + } + + /** + * Activates status message output to a PSR3 logger + */ + public function setLogger(LoggerInterface $logger): self + { + $this->statusWriter->setLogger($logger); + return $this; + } + + /** + * Sets the main script location if it cannot be called from argv + */ + public function setMainScript(string $script): self + { + $this->script = $script; + return $this; + } + + /** + * Persist the settings to keep Xdebug out of sub-processes + */ + public function setPersistent(): self + { + $this->persistent = true; + return $this; + } + + /** + * Checks if Xdebug is loaded and the process needs to be restarted + * + * This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG + * environment variable to 1. This variable is used internally so that + * the restarted process is created only once. + */ + public function check(): void + { + $this->notify(Status::CHECK, self::$xdebugVersion.'|'.self::$xdebugMode); + $envArgs = explode('|', (string) getenv($this->envAllowXdebug)); + + if (!((bool) $envArgs[0]) && $this->requiresRestart(self::$xdebugActive)) { + // Restart required + $this->notify(Status::RESTART); + $command = $this->prepareRestart(); + + if ($command !== null) { + $this->restart($command); + } + return; + } + + if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) { + // Restarted, so unset environment variable and use saved values + $this->notify(Status::RESTARTED); + + Process::setEnv($this->envAllowXdebug); + self::$inRestart = true; + + if (self::$xdebugVersion === null) { + // Skipped version is only set if Xdebug is not loaded + self::$skipped = $envArgs[1]; + } + + $this->tryEnableSignals(); + + // Put restart settings in the environment + $this->setEnvRestartSettings($envArgs); + return; + } + + $this->notify(Status::NORESTART); + $settings = self::getRestartSettings(); + + if ($settings !== null) { + // Called with existing settings, so sync our settings + $this->syncSettings($settings); + } + } + + /** + * Returns an array of php.ini locations with at least one entry + * + * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files. + * The loaded ini location is the first entry and may be an empty string. + * + * @return non-empty-list + */ + public static function getAllIniFiles(): array + { + if (self::$name !== null) { + $env = getenv(self::$name.self::SUFFIX_INIS); + + if (false !== $env) { + return explode(PATH_SEPARATOR, $env); + } + } + + $paths = [(string) php_ini_loaded_file()]; + $scanned = php_ini_scanned_files(); + + if ($scanned !== false) { + $paths = array_merge($paths, array_map('trim', explode(',', $scanned))); + } + + return $paths; + } + + /** + * Returns an array of restart settings or null + * + * Settings will be available if the current process was restarted, or + * called with the settings from an existing restart. + * + * @phpstan-return restartData|null + */ + public static function getRestartSettings(): ?array + { + $envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS)); + + if (count($envArgs) !== 6 + || (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) { + return null; + } + + return [ + 'tmpIni' => $envArgs[0], + 'scannedInis' => (bool) $envArgs[1], + 'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2], + 'phprc' => '*' === $envArgs[3] ? false : $envArgs[3], + 'inis' => explode(PATH_SEPARATOR, $envArgs[4]), + 'skipped' => $envArgs[5], + ]; + } + + /** + * Returns the Xdebug version that triggered a successful restart + */ + public static function getSkippedVersion(): string + { + return (string) self::$skipped; + } + + /** + * Returns whether Xdebug is loaded and active + * + * true: if Xdebug is loaded and is running in an active mode. + * false: if Xdebug is not loaded, or it is running with xdebug.mode=off. + */ + public static function isXdebugActive(): bool + { + self::setXdebugDetails(); + return self::$xdebugActive; + } + + /** + * Allows an extending class to decide if there should be a restart + * + * The default is to restart if Xdebug is loaded and its mode is not "off". + */ + protected function requiresRestart(bool $default): bool + { + return $default; + } + + /** + * Allows an extending class to access the tmpIni + * + * @param non-empty-list $command + */ + protected function restart(array $command): void + { + $this->doRestart($command); + } + + /** + * Executes the restarted command then deletes the tmp ini + * + * @param non-empty-list $command + * @phpstan-return never + */ + private function doRestart(array $command): void + { + if (PHP_VERSION_ID >= 70400) { + $cmd = $command; + $displayCmd = sprintf('[%s]', implode(', ', $cmd)); + } else { + $cmd = Process::escapeShellCommand($command); + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + // Outer quotes required on cmd string below PHP 8 + $cmd = '"'.$cmd.'"'; + } + $displayCmd = $cmd; + } + + $this->tryEnableSignals(); + $this->notify(Status::RESTARTING, $displayCmd); + + $process = proc_open($cmd, [], $pipes); + if (is_resource($process)) { + $exitCode = proc_close($process); + } + + if (!isset($exitCode)) { + // Unlikely that php or the default shell cannot be invoked + $this->notify(Status::ERROR, 'Unable to restart process'); + $exitCode = -1; + } else { + $this->notify(Status::INFO, 'Restarted process exited '.$exitCode); + } + + if ($this->debug === '2') { + $this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni); + } else { + @unlink((string) $this->tmpIni); + } + + exit($exitCode); + } + + /** + * Returns the command line array if everything was written for the restart + * + * If any of the following fails (however unlikely) we must return false to + * stop potential recursion: + * - tmp ini file creation + * - environment variable creation + * + * @return non-empty-list|null + */ + private function prepareRestart(): ?array + { + if (!$this->cli) { + $this->notify(Status::ERROR, 'Unsupported SAPI: '.PHP_SAPI); + return null; + } + + if (($argv = $this->checkServerArgv()) === null) { + $this->notify(Status::ERROR, '$_SERVER[argv] is not as expected'); + return null; + } + + if (!$this->checkConfiguration($info)) { + $this->notify(Status::ERROR, $info); + return null; + } + + $mainScript = (string) $this->script; + if (!$this->checkMainScript($mainScript, $argv)) { + $this->notify(Status::ERROR, 'Unable to access main script: '.$mainScript); + return null; + } + + $tmpDir = sys_get_temp_dir(); + $iniError = 'Unable to create temp ini file at: '.$tmpDir; + + if (($tmpfile = @tempnam($tmpDir, '')) === false) { + $this->notify(Status::ERROR, $iniError); + return null; + } + + $error = null; + $iniFiles = self::getAllIniFiles(); + $scannedInis = count($iniFiles) > 1; + + if (!$this->writeTmpIni($tmpfile, $iniFiles, $error)) { + $this->notify(Status::ERROR, $error ?? $iniError); + @unlink($tmpfile); + return null; + } + + if (!$this->setEnvironment($scannedInis, $iniFiles, $tmpfile)) { + $this->notify(Status::ERROR, 'Unable to set environment variables'); + @unlink($tmpfile); + return null; + } + + $this->tmpIni = $tmpfile; + + return $this->getCommand($argv, $tmpfile, $mainScript); + } + + /** + * Returns true if the tmp ini file was written + * + * @param non-empty-list $iniFiles All ini files used in the current process + */ + private function writeTmpIni(string $tmpFile, array $iniFiles, ?string &$error): bool + { + // $iniFiles has at least one item and it may be empty + if ($iniFiles[0] === '') { + array_shift($iniFiles); + } + + $content = ''; + $sectionRegex = '/^\s*\[(?:PATH|HOST)\s*=/mi'; + $xdebugRegex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi'; + + foreach ($iniFiles as $file) { + // Check for inaccessible ini files + if (($data = @file_get_contents($file)) === false) { + $error = 'Unable to read ini: '.$file; + return false; + } + // Check and remove directives after HOST and PATH sections + if (Preg::isMatchWithOffsets($sectionRegex, $data, $matches)) { + $data = substr($data, 0, $matches[0][1]); + } + $content .= Preg::replace($xdebugRegex, ';$1', $data).PHP_EOL; + } + + // Merge loaded settings into our ini content, if it is valid + $config = parse_ini_string($content); + $loaded = ini_get_all(null, false); + + if (false === $config || false === $loaded) { + $error = 'Unable to parse ini data'; + return false; + } + + $content .= $this->mergeLoadedConfig($loaded, $config); + + // Work-around for https://bugs.php.net/bug.php?id=75932 + $content .= 'opcache.enable_cli=0'.PHP_EOL; + + return (bool) @file_put_contents($tmpFile, $content); + } + + /** + * Returns the command line arguments for the restart + * + * @param non-empty-list $argv + * @return non-empty-list + */ + private function getCommand(array $argv, string $tmpIni, string $mainScript): array + { + $php = [PHP_BINARY]; + $args = array_slice($argv, 1); + + if (!$this->persistent) { + // Use command-line options + array_push($php, '-n', '-c', $tmpIni); + } + + return array_merge($php, [$mainScript], $args); + } + + /** + * Returns true if the restart environment variables were set + * + * No need to update $_SERVER since this is set in the restarted process. + * + * @param non-empty-list $iniFiles All ini files used in the current process + */ + private function setEnvironment(bool $scannedInis, array $iniFiles, string $tmpIni): bool + { + $scanDir = getenv('PHP_INI_SCAN_DIR'); + $phprc = getenv('PHPRC'); + + // Make original inis available to restarted process + if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) { + return false; + } + + if ($this->persistent) { + // Use the environment to persist the settings + if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$tmpIni)) { + return false; + } + } + + // Flag restarted process and save values for it to use + $envArgs = [ + self::RESTART_ID, + self::$xdebugVersion, + (int) $scannedInis, + false === $scanDir ? '*' : $scanDir, + false === $phprc ? '*' : $phprc, + ]; + + return putenv($this->envAllowXdebug.'='.implode('|', $envArgs)); + } + + /** + * Logs status messages + */ + private function notify(string $op, ?string $data = null): void + { + $this->statusWriter->report($op, $data); + } + + /** + * Returns default, changed and command-line ini settings + * + * @param mixed[] $loadedConfig All current ini settings + * @param mixed[] $iniConfig Settings from user ini files + * + */ + private function mergeLoadedConfig(array $loadedConfig, array $iniConfig): string + { + $content = ''; + + foreach ($loadedConfig as $name => $value) { + // Value will either be null, string or array (HHVM only) + if (!is_string($value) + || strpos($name, 'xdebug') === 0 + || $name === 'apc.mmap_file_mask') { + continue; + } + + if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { + // Double-quote escape each value + $content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL; + } + } + + return $content; + } + + /** + * Returns true if the script name can be used + * + * @param non-empty-list $argv + */ + private function checkMainScript(string &$mainScript, array $argv): bool + { + if ($mainScript !== '') { + // Allow an application to set -- for standard input + return file_exists($mainScript) || '--' === $mainScript; + } + + if (file_exists($mainScript = $argv[0])) { + return true; + } + + // Use a backtrace to resolve Phar and chdir issues. + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $main = end($trace); + + if ($main !== false && isset($main['file'])) { + return file_exists($mainScript = $main['file']); + } + + return false; + } + + /** + * Adds restart settings to the environment + * + * @param non-empty-list $envArgs + */ + private function setEnvRestartSettings(array $envArgs): void + { + $settings = [ + php_ini_loaded_file(), + $envArgs[2], + $envArgs[3], + $envArgs[4], + getenv($this->envOriginalInis), + self::$skipped, + ]; + + Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings)); + } + + /** + * Syncs settings and the environment if called with existing settings + * + * @phpstan-param restartData $settings + */ + private function syncSettings(array $settings): void + { + if (false === getenv($this->envOriginalInis)) { + // Called by another app, so make original inis available + Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis'])); + } + + self::$skipped = $settings['skipped']; + $this->notify(Status::INFO, 'Process called with existing restart settings'); + } + + /** + * Returns true if there are no known configuration issues + */ + private function checkConfiguration(?string &$info): bool + { + if (!function_exists('proc_open')) { + $info = 'proc_open function is disabled'; + return false; + } + + if (!file_exists(PHP_BINARY)) { + $info = 'PHP_BINARY is not available'; + return false; + } + + if (extension_loaded('uopz') && !((bool) ini_get('uopz.disable'))) { + // uopz works at opcode level and disables exit calls + if (function_exists('uopz_allow_exit')) { + @uopz_allow_exit(true); + } else { + $info = 'uopz extension is not compatible'; + return false; + } + } + + // Check UNC paths when using cmd.exe + if (defined('PHP_WINDOWS_VERSION_BUILD') && PHP_VERSION_ID < 70400) { + $workingDir = getcwd(); + + if ($workingDir === false) { + $info = 'unable to determine working directory'; + return false; + } + + if (0 === strpos($workingDir, '\\\\')) { + $info = 'cmd.exe does not support UNC paths: '.$workingDir; + return false; + } + } + + return true; + } + + /** + * Enables async signals and control interrupts in the restarted process + * + * Available on Unix PHP 7.1+ with the pcntl extension and Windows PHP 7.4+. + */ + private function tryEnableSignals(): void + { + if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { + pcntl_async_signals(true); + $message = 'Async signals enabled'; + + if (!self::$inRestart) { + // Restarting, so ignore SIGINT in parent + pcntl_signal(SIGINT, SIG_IGN); + } elseif (is_int(pcntl_signal_get_handler(SIGINT))) { + // Restarted, no handler set so force default action + pcntl_signal(SIGINT, SIG_DFL); + } + } + + if (!self::$inRestart && function_exists('sapi_windows_set_ctrl_handler')) { + // Restarting, so set a handler to ignore CTRL events in the parent. + // This ensures that CTRL+C events will be available in the child + // process without having to enable them there, which is unreliable. + sapi_windows_set_ctrl_handler(function ($evt) {}); + } + } + + /** + * Returns $_SERVER['argv'] if it is as expected + * + * @return non-empty-list|null + */ + private function checkServerArgv(): ?array + { + $result = []; + + if (isset($_SERVER['argv']) && is_array($_SERVER['argv'])) { + foreach ($_SERVER['argv'] as $value) { + if (!is_string($value)) { + return null; + } + + $result[] = $value; + } + } + + return count($result) > 0 ? $result : null; + } + + /** + * Sets static properties $xdebugActive, $xdebugVersion and $xdebugMode + */ + private static function setXdebugDetails(): void + { + if (self::$xdebugActive !== null) { + return; + } + + self::$xdebugActive = false; + if (!extension_loaded('xdebug')) { + return; + } + + $version = phpversion('xdebug'); + self::$xdebugVersion = $version !== false ? $version : 'unknown'; + + if (version_compare(self::$xdebugVersion, '3.1', '>=')) { + $modes = xdebug_info('mode'); + self::$xdebugMode = count($modes) === 0 ? 'off' : implode(',', $modes); + self::$xdebugActive = self::$xdebugMode !== 'off'; + return; + } + + // See if xdebug.mode is supported in this version + $iniMode = ini_get('xdebug.mode'); + if ($iniMode === false) { + self::$xdebugActive = true; + return; + } + + // Environment value wins but cannot be empty + $envMode = (string) getenv('XDEBUG_MODE'); + if ($envMode !== '') { + self::$xdebugMode = $envMode; + } else { + self::$xdebugMode = $iniMode !== '' ? $iniMode : 'off'; + } + + // An empty comma-separated list is treated as mode 'off' + if (Preg::isMatch('/^,+$/', str_replace(' ', '', self::$xdebugMode))) { + self::$xdebugMode = 'off'; + } + + self::$xdebugActive = self::$xdebugMode !== 'off'; + } +} diff --git a/trilhas_poo/vendor/ergebnis/agent-detector/CHANGELOG.md b/trilhas_poo/vendor/ergebnis/agent-detector/CHANGELOG.md new file mode 100644 index 0000000..26d6bcb --- /dev/null +++ b/trilhas_poo/vendor/ergebnis/agent-detector/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +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). + +## Unreleased + +For a full diff see [`1.2.0...main`][1.2.0...main]. + +## [`1.2.0`][1.2.0] + +For a full diff see [`1.1.1...1.2.0`][1.1.1...1.2.0]. + +### Added + +- Added support for detecting the presence of an agent when the `COPILOT_CLI` or `PI_CODING_AGENT` environment variables are set ([#10]), by [@raphaelstolt] + +## [`1.1.1`][1.1.1] + +For a full diff see [`1.1.0...1.1.1`][1.1.0...1.1.1]. + +### Fixed + +- Allowed installation on PHP 8.6 ([#4]), by [@localheinz] + +## [`1.1.0`][1.1.0] + +For a full diff see [`1.0.1...1.1.0`][1.0.1...1.1.0]. + +### Added + +- Added support for detecting the presence of an agent when the `CURSOR_EXTENSION_HOST_ROLE` environment variable is set ([#2]), by [@localheinz] + +## [`1.0.1`][1.0.1] + +For a full diff see [`2655ea1...1.0.1`][2655ea1...1.0.1]. + +### Added + +- Added `Detector` ([#1]), by [@localheinz] + +[1.0.1]: https://github.com/ergebnis/agent-detector/releases/tag/1.0.1 +[1.1.0]: https://github.com/ergebnis/agent-detector/releases/tag/1.1.0 +[1.1.1]: https://github.com/ergebnis/agent-detector/releases/tag/1.1.1 +[1.2.0]: https://github.com/ergebnis/agent-detector/releases/tag/1.2.0 + +[2655ea1...1.0.1]: https://github.com/ergebnis/agent-detector/compare/2655ea1...1.0.1 +[1.0.1...1.1.0]: https://github.com/ergebnis/agent-detector/compare/1.0.1...1.1.0 +[1.1.0...1.1.1]: https://github.com/ergebnis/agent-detector/compare/1.1.0...1.1.1 +[1.1.1...1.2.0]: https://github.com/ergebnis/agent-detector/compare/1.1.1...1.2.0 +[1.2.0...main]: https://github.com/ergebnis/agent-detector/compare/1.2.0...main + +[#1]: https://github.com/ergebnis/agent-detector/pull/1 +[#2]: https://github.com/ergebnis/agent-detector/pull/2 +[#4]: https://github.com/ergebnis/agent-detector/pull/4 +[#10]: https://github.com/ergebnis/agent-detector/pull/10 + +[@localheinz]: https://github.com/localheinz +[@raphaelstolt]: https://github.com/raphaelstolt diff --git a/trilhas_poo/vendor/ergebnis/agent-detector/LICENSE.md b/trilhas_poo/vendor/ergebnis/agent-detector/LICENSE.md new file mode 100644 index 0000000..bb32be1 --- /dev/null +++ b/trilhas_poo/vendor/ergebnis/agent-detector/LICENSE.md @@ -0,0 +1,16 @@ +# The MIT License (MIT) + +Copyright (c) 2026 Andreas Möller + +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/trilhas_poo/vendor/ergebnis/agent-detector/README.md b/trilhas_poo/vendor/ergebnis/agent-detector/README.md new file mode 100644 index 0000000..c73d391 --- /dev/null +++ b/trilhas_poo/vendor/ergebnis/agent-detector/README.md @@ -0,0 +1,107 @@ +# agent-detector + +[![Integrate](https://github.com/ergebnis/agent-detector/actions/workflows/integrate.yaml/badge.svg?branch=main)](https://github.com/ergebnis/agent-detector/actions/workflows/integrate.yaml) +[![Merge](https://github.com/ergebnis/agent-detector/actions/workflows/merge.yaml/badge.svg)](https://github.com/ergebnis/agent-detector/actions/workflows/merge.yaml) +[![Release](https://github.com/ergebnis/agent-detector/actions/workflows/release.yaml/badge.svg)](https://github.com/ergebnis/agent-detector/actions/workflows/release.yaml) +[![Renew](https://github.com/ergebnis/agent-detector/actions/workflows/renew.yaml/badge.svg)](https://github.com/ergebnis/agent-detector/actions/workflows/renew.yaml) + +[![Code Coverage](https://codecov.io/gh/ergebnis/agent-detector/branch/main/graph/badge.svg)](https://codecov.io/gh/ergebnis/agent-detector) + +[![Latest Stable Version](https://poser.pugx.org/ergebnis/agent-detector/v/stable)](https://packagist.org/packages/ergebnis/agent-detector) +[![Total Downloads](https://poser.pugx.org/ergebnis/agent-detector/downloads)](https://packagist.org/packages/ergebnis/agent-detector) +[![Monthly Downloads](http://poser.pugx.org/ergebnis/agent-detector/d/monthly)](https://packagist.org/packages/ergebnis/agent-detector) + +This project provides a [`composer`](https://getcomposer.org) package with a detector for detecting the presence of an agent. + +## Installation + +Run + +```sh +composer require ergebnis/agent-detector +``` + +## Usage + +### Detecting the presence of an agent + +```php +isAgentPresent(\getenv()); +``` + +### Supported agents + +This package detects the presence of the following agents via environment variables: + +| Agent | Environment Variable | +|---|---| +| [Amp](https://amp.dev) | `AMP_CURRENT_THREAD_ID` | +| [Antigravity](https://antigravity.dev) | `ANTIGRAVITY_AGENT` | +| [Augment](https://augmentcode.com) | `AUGMENT_AGENT` | +| [Claude Code](https://github.com/anthropics/claude-code) | `CLAUDECODE`, `CLAUDE_CODE`, `CLAUDE_CODE_IS_COWORK` | +| [Codex](https://github.com/openai/codex) | `CODEX_CI`, `CODEX_SANDBOX`, `CODEX_THREAD_ID` | +| [Cursor](https://cursor.com) | `CURSOR_AGENT`, `CURSOR_EXTENSION_HOST_ROLE`, `CURSOR_TRACE_ID` | +| [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `GEMINI_CLI` | +| [GitHub Copilot](https://github.com/features/copilot) | `COPILOT_ALLOW_ALL`, `COPILOT_CLI`, `COPILOT_GITHUB_TOKEN`, `COPILOT_MODEL | +| [OpenCode](https://github.com/sst/opencode) | `OPENCODE`, `OPENCODE_CLIENT` | +| [Pi](https://pi.dev) | `PI_CODING_AGENT` | +| [Replit](https://replit.com) | `REPL_ID` | + +### Indicating the presence of an agent + +In addition, the generic `AI_AGENT` environment variable can be set to indicate the presence of an agent. + +## Changelog + +The maintainers of this project record notable changes to this project in a [changelog](CHANGELOG.md). + +## Contributing + +The maintainers of this project suggest following the [contribution guide](.github/CONTRIBUTING.md). + +## Code of Conduct + +The maintainers of this project ask contributors to follow the [code of conduct](https://github.com/ergebnis/.github/blob/main/CODE_OF_CONDUCT.md). + +## General Support Policy + +The maintainers of this project provide limited support. + +## PHP Version Support Policy + +This project currently supports the following PHP versions: + +- [PHP 7.4](https://www.php.net/releases/#7.4.0) (has reached its end of life on November 28, 2022) +- [PHP 8.0](https://www.php.net/releases/#8.0.0) (has reached its end of life on November 26, 2023) +- [PHP 8.1](https://www.php.net/releases/#8.1.0) (has reached its end of life on December 31, 2025) +- [PHP 8.2](https://www.php.net/releases/#8.2.0) +- [PHP 8.3](https://www.php.net/releases/#8.3.0) +- [PHP 8.4](https://www.php.net/releases/#8.4.0) +- [PHP 8.5](https://www.php.net/releases/#8.5.0) + +The maintainers of this project add support for a PHP version following its initial release and _may_ drop support for a PHP version when it has reached its [end of life](https://www.php.net/supported-versions.php). + +## Security Policy + +This project has a [security policy](.github/SECURITY.md). + +## License + +This project uses the [MIT license](LICENSE.md). + + +## Credits + +The agent detector is inspired by [`shipfastlabs/agent-detector`](https://github.com/shipfastlabs/agent-detector), originally licensed under MIT by [Pushpak Chhajed](https://github.com/pushpak1300). + +## Social + +Follow [@localheinz](https://twitter.com/intent/follow?screen_name=localheinz) and [@ergebnis](https://twitter.com/intent/follow?screen_name=ergebnis) on Twitter. diff --git a/trilhas_poo/vendor/ergebnis/agent-detector/composer.json b/trilhas_poo/vendor/ergebnis/agent-detector/composer.json new file mode 100644 index 0000000..fa88ce2 --- /dev/null +++ b/trilhas_poo/vendor/ergebnis/agent-detector/composer.json @@ -0,0 +1,74 @@ +{ + "name": "ergebnis/agent-detector", + "description": "Provides a detector for detecting the presence of an agent.", + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Andreas Möller", + "email": "am@localheinz.com", + "homepage": "https://localheinz.com" + } + ], + "homepage": "https://github.com/ergebnis/agent-detector", + "support": { + "issues": "https://github.com/ergebnis/agent-detector/issues", + "source": "https://github.com/ergebnis/agent-detector", + "security": "https://github.com/ergebnis/agent-detector/blob/main/.github/SECURITY.md" + }, + "require": { + "php": "~7.4.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.51.0", + "ergebnis/license": "^2.7.0", + "ergebnis/php-cs-fixer-config": "^6.60.2", + "ergebnis/phpstan-rules": "^2.13.1", + "ergebnis/phpunit-slow-test-detector": "^2.24.0", + "ergebnis/rector-rules": "^1.18.1", + "fakerphp/faker": "^1.24.1", + "infection/infection": "^0.26.6", + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^2.1.54", + "phpstan/phpstan-deprecation-rules": "^2.0.4", + "phpstan/phpstan-phpunit": "^2.0.16", + "phpstan/phpstan-strict-rules": "^2.0.10", + "phpunit/phpunit": "^9.6.34", + "rector/rector": "^2.4.2" + }, + "autoload": { + "psr-4": { + "Ergebnis\\AgentDetector\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Ergebnis\\AgentDetector\\Test\\": "test/" + } + }, + "config": { + "allow-plugins": { + "composer/package-versions-deprecated": true, + "ergebnis/composer-normalize": true, + "infection/extension-installer": true, + "phpstan/extension-installer": true + }, + "audit": { + "abandoned": "report" + }, + "platform": { + "php": "7.4.33" + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-main": "1.2-dev" + }, + "composer-normalize": { + "indent-size": 2, + "indent-style": "space" + } + } +} diff --git a/trilhas_poo/vendor/ergebnis/agent-detector/src/Detector.php b/trilhas_poo/vendor/ergebnis/agent-detector/src/Detector.php new file mode 100644 index 0000000..54f3bdb --- /dev/null +++ b/trilhas_poo/vendor/ergebnis/agent-detector/src/Detector.php @@ -0,0 +1,68 @@ + + */ + private const AGENT_ENVIRONMENT_VARIABLES = [ + 'AI_AGENT' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'AMP_CURRENT_THREAD_ID' => 'https://github.com/shipfastlabs/agent-detector/blob/main/src/AgentDetector.php', + 'ANTIGRAVITY_AGENT' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'AUGMENT_AGENT' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CLAUDECODE' => 'https://github.com/anthropics/claude-code/blob/main/src/utils/env.ts', + 'CLAUDE_CODE' => 'https://github.com/anthropics/claude-code/blob/main/src/utils/env.ts', + 'CLAUDE_CODE_IS_COWORK' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CODEX_CI' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CODEX_SANDBOX' => 'https://github.com/openai/codex/blob/main/codex-rs/core/src/seatbelt.rs', + 'CODEX_THREAD_ID' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'COPILOT_ALLOW_ALL' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'COPILOT_CLI' => 'https://github.com/github/copilot-cli', + 'COPILOT_GITHUB_TOKEN' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'COPILOT_MODEL' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CURSOR_AGENT' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CURSOR_EXTENSION_HOST_ROLE' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'CURSOR_TRACE_ID' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + 'GEMINI_CLI' => 'https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/tools/shell/shell-tool.ts', + 'OPENCODE' => 'https://github.com/shipfastlabs/agent-detector/blob/main/src/AgentDetector.php', + 'OPENCODE_CLIENT' => 'https://github.com/sst/opencode/blob/dev/packages/opencode/src/flag/flag.ts', + 'PI_CODING_AGENT' => 'https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/index.ts', + 'REPL_ID' => 'https://github.com/vercel/vercel/blob/main/packages/detect-agent/src/index.ts', + ]; + + /** + * @param array $environmentVariables + */ + public function isAgentPresent(array $environmentVariables): bool + { + foreach (self::AGENT_ENVIRONMENT_VARIABLES as $variable => $url) { + if (\array_key_exists($variable, $environmentVariables)) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/evenement/evenement/.gitattributes b/trilhas_poo/vendor/evenement/evenement/.gitattributes new file mode 100644 index 0000000..8e493b8 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/.gitattributes @@ -0,0 +1,7 @@ +/.github export-ignore +/doc export-ignore +/examples export-ignore +/tests export-ignore +/.gitignore export-ignore +/CHANGELOG.md export-ignore +/phpunit.xml.dist export-ignore diff --git a/trilhas_poo/vendor/evenement/evenement/LICENSE b/trilhas_poo/vendor/evenement/evenement/LICENSE new file mode 100644 index 0000000..d9a37d0 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Igor Wiedler + +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/trilhas_poo/vendor/evenement/evenement/README.md b/trilhas_poo/vendor/evenement/evenement/README.md new file mode 100644 index 0000000..455dd22 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/README.md @@ -0,0 +1,64 @@ +# Événement + +Événement is a very simple event dispatching library for PHP. + +It has the same design goals as [Silex](https://silex.symfony.com/) and +[Pimple](https://github.com/silexphp/Pimple), to empower the user while staying concise +and simple. + +It is very strongly inspired by the [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter) API found in +[node.js](http://nodejs.org). + +![Continuous Integration](https://github.com/igorw/evenement/workflows/CI/badge.svg) +[![Latest Stable Version](https://poser.pugx.org/evenement/evenement/v/stable.png)](https://packagist.org/packages/evenement/evenement) +[![Total Downloads](https://poser.pugx.org/evenement/evenement/downloads.png)](https://packagist.org/packages/evenement/evenement/stats) +[![License](https://poser.pugx.org/evenement/evenement/license.png)](https://packagist.org/packages/evenement/evenement) + +## Fetch + +The recommended way to install Événement is [through composer](http://getcomposer.org). By running the following command: + + $ composer require evenement/evenement + +## Usage + +### Creating an Emitter + +```php +on('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +### Removing Listeners + +```php +removeListener('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +### Emitting Events + +```php +emit('user.created', [$user]); +``` + +Tests +----- + + $ ./vendor/bin/phpunit + +License +------- +MIT, see LICENSE. diff --git a/trilhas_poo/vendor/evenement/evenement/composer.json b/trilhas_poo/vendor/evenement/evenement/composer.json new file mode 100644 index 0000000..5444d93 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/composer.json @@ -0,0 +1,29 @@ +{ + "name": "evenement/evenement", + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": ["event-dispatcher", "event-emitter"], + "license": "MIT", + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^9 || ^6" + }, + "autoload": { + "psr-4": { + "Evenement\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Evenement\\Tests\\": "tests/" + }, + "files": ["tests/functions.php"] + } +} diff --git a/trilhas_poo/vendor/evenement/evenement/src/EventEmitter.php b/trilhas_poo/vendor/evenement/evenement/src/EventEmitter.php new file mode 100644 index 0000000..db189b9 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/src/EventEmitter.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +class EventEmitter implements EventEmitterInterface +{ + use EventEmitterTrait; +} diff --git a/trilhas_poo/vendor/evenement/evenement/src/EventEmitterInterface.php b/trilhas_poo/vendor/evenement/evenement/src/EventEmitterInterface.php new file mode 100644 index 0000000..310631a --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/src/EventEmitterInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +interface EventEmitterInterface +{ + public function on($event, callable $listener); + public function once($event, callable $listener); + public function removeListener($event, callable $listener); + public function removeAllListeners($event = null); + public function listeners($event = null); + public function emit($event, array $arguments = []); +} diff --git a/trilhas_poo/vendor/evenement/evenement/src/EventEmitterTrait.php b/trilhas_poo/vendor/evenement/evenement/src/EventEmitterTrait.php new file mode 100644 index 0000000..1503429 --- /dev/null +++ b/trilhas_poo/vendor/evenement/evenement/src/EventEmitterTrait.php @@ -0,0 +1,154 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +use InvalidArgumentException; + +use function count; +use function array_keys; +use function array_merge; +use function array_search; +use function array_unique; +use function array_values; + +trait EventEmitterTrait +{ + protected $listeners = []; + protected $onceListeners = []; + + public function on($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (!isset($this->listeners[$event])) { + $this->listeners[$event] = []; + } + + $this->listeners[$event][] = $listener; + + return $this; + } + + public function once($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (!isset($this->onceListeners[$event])) { + $this->onceListeners[$event] = []; + } + + $this->onceListeners[$event][] = $listener; + + return $this; + } + + public function removeListener($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (isset($this->listeners[$event])) { + $index = array_search($listener, $this->listeners[$event], true); + if (false !== $index) { + unset($this->listeners[$event][$index]); + if (count($this->listeners[$event]) === 0) { + unset($this->listeners[$event]); + } + } + } + + if (isset($this->onceListeners[$event])) { + $index = array_search($listener, $this->onceListeners[$event], true); + if (false !== $index) { + unset($this->onceListeners[$event][$index]); + if (count($this->onceListeners[$event]) === 0) { + unset($this->onceListeners[$event]); + } + } + } + } + + public function removeAllListeners($event = null) + { + if ($event !== null) { + unset($this->listeners[$event]); + } else { + $this->listeners = []; + } + + if ($event !== null) { + unset($this->onceListeners[$event]); + } else { + $this->onceListeners = []; + } + } + + public function listeners($event = null): array + { + if ($event === null) { + $events = []; + $eventNames = array_unique( + array_merge( + array_keys($this->listeners), + array_keys($this->onceListeners) + ) + ); + foreach ($eventNames as $eventName) { + $events[$eventName] = array_merge( + isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : [], + isset($this->onceListeners[$eventName]) ? $this->onceListeners[$eventName] : [] + ); + } + return $events; + } + + return array_merge( + isset($this->listeners[$event]) ? $this->listeners[$event] : [], + isset($this->onceListeners[$event]) ? $this->onceListeners[$event] : [] + ); + } + + public function emit($event, array $arguments = []) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + $listeners = []; + if (isset($this->listeners[$event])) { + $listeners = array_values($this->listeners[$event]); + } + + $onceListeners = []; + if (isset($this->onceListeners[$event])) { + $onceListeners = array_values($this->onceListeners[$event]); + } + + if(empty($listeners) === false) { + foreach ($listeners as $listener) { + $listener(...$arguments); + } + } + + if(empty($onceListeners) === false) { + unset($this->onceListeners[$event]); + foreach ($onceListeners as $listener) { + $listener(...$arguments); + } + } + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/.envrc b/trilhas_poo/vendor/fidry/cpu-core-counter/.envrc new file mode 100644 index 0000000..a7c02ef --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/.envrc @@ -0,0 +1,5 @@ +use nix --packages \ + gnumake \ + yamllint + +source_env_if_exists .envrc.local diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/LICENSE.md b/trilhas_poo/vendor/fidry/cpu-core-counter/LICENSE.md new file mode 100644 index 0000000..0244213 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/LICENSE.md @@ -0,0 +1,16 @@ +# The MIT License (MIT) + +Copyright (c) 2022 Théo FIDRY + +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/trilhas_poo/vendor/fidry/cpu-core-counter/README.md b/trilhas_poo/vendor/fidry/cpu-core-counter/README.md new file mode 100644 index 0000000..6b554d2 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/README.md @@ -0,0 +1,138 @@ +# CPU Core Counter + +This package is a tiny utility to get the number of CPU cores. + +```sh +composer require fidry/cpu-core-counter +``` + + +## Usage + +```php +use Fidry\CpuCoreCounter\CpuCoreCounter; +use Fidry\CpuCoreCounter\NumberOfCpuCoreNotFound; +use Fidry\CpuCoreCounter\Finder\DummyCpuCoreFinder; + +$counter = new CpuCoreCounter(); + +// For knowing the number of cores you can use for launching parallel processes: +$counter->getAvailableForParallelisation()->availableCpus; + +// Get the number of CPU cores (by default it will use the logical cores count): +try { + $counter->getCount(); // e.g. 8 +} catch (NumberOfCpuCoreNotFound) { + return 1; // Fallback value +} + +// An alternative form where we not want to catch the exception: + +$counter = new CpuCoreCounter([ + ...CpuCoreCounter::getDefaultFinders(), + new DummyCpuCoreFinder(1), // Fallback value +]); + +// A type-safe alternative form: +$counter->getCountWithFallback(1); + +// Note that the result is memoized. +$counter->getCount(); // e.g. 8 + +``` + + +## Advanced usage + +### Changing the finders + +When creating `CpuCoreCounter`, you may want to change the order of the finders +used or disable a specific finder. You can easily do so by passing the finders +you want + +```php +// Remove WindowsWmicFinder +$finders = array_filter( + CpuCoreCounter::getDefaultFinders(), + static fn (CpuCoreFinder $finder) => !($finder instanceof WindowsWmicFinder) +); + +$cores = (new CpuCoreCounter($finders))->getCount(); +``` + +```php +// Use CPUInfo first & don't use Nproc +$finders = [ + new CpuInfoFinder(), + new WindowsWmicFinder(), + new HwLogicalFinder(), +]; + +$cores = (new CpuCoreCounter($finders))->getCount(); +``` + +### Choosing only logical or physical finders + +`FinderRegistry` provides two helpful entries: + +- `::getDefaultLogicalFinders()`: gives an ordered list of finders that will + look for the _logical_ CPU cores count. +- `::getDefaultPhysicalFinders()`: gives an ordered list of finders that will + look for the _physical_ CPU cores count. + +By default, when using `CpuCoreCounter`, it will use the logical finders since +it is more likely what you are looking for and is what is used by PHP source to +build the PHP binary. + + +### Checks what finders find what on your system + +You have three scrips available that provides insight about what the finders +can find: + +```shell +# Checks what each given finder will find on your system with details about the +# information it had. +make diagnose # From this repository +./vendor/fidry/cpu-core-counter/bin/diagnose.php # From the library +``` + +And: +```shell +# Execute all finders and display the result they found. +make execute # From this repository +./vendor/fidry/cpu-core-counter/bin/execute.php # From the library +``` + + +### Debug the results found + +You have 3 methods available to help you find out what happened: + +1. If you are using the default configuration of finder registries, you can check + the previous section which will provide plenty of information. +2. If what you are interested in is how many CPU cores were found, you can use + the `CpuCoreCounter::trace()` method. +3. If what you are interested in is how the calculation of CPU cores available + for parallelisation was done, you can inspect the values of `ParallelisationResult` + returned by `CpuCoreCounter::getAvailableForParallelisation()`. + + +## Backward Compatibility Promise (BCP) + +The policy is for the major part following the same as [Symfony's one][symfony-bc-policy]. +Note that the code marked as `@private` or `@internal` are excluded from the BCP. + +The following elements are also excluded: + +- The `diagnose` and `execute` commands: those are for debugging/inspection purposes only +- `FinderRegistry::get*Finders()`: new finders may be added or the order of finders changed at any time + + +## License + +This package is licensed using the MIT License. + +Please have a look at [`LICENSE.md`](LICENSE.md). + +[symfony-bc-policy]: https://symfony.com/doc/current/contributing/code/bc.html diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/bin/diagnose.php b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/diagnose.php new file mode 100755 index 0000000..7dd894a --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/diagnose.php @@ -0,0 +1,27 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use Fidry\CpuCoreCounter\Diagnoser; +use Fidry\CpuCoreCounter\Finder\FinderRegistry; + +require_once __DIR__.'/../vendor/autoload.php'; + +echo 'Running diagnosis...'.PHP_EOL.PHP_EOL; +echo Diagnoser::diagnose(FinderRegistry::getAllVariants()).PHP_EOL; + +echo 'Logical CPU cores finders...'.PHP_EOL.PHP_EOL; +echo Diagnoser::diagnose(FinderRegistry::getDefaultLogicalFinders()).PHP_EOL; + +echo 'Physical CPU cores finders...'.PHP_EOL.PHP_EOL; +echo Diagnoser::diagnose(FinderRegistry::getDefaultPhysicalFinders()).PHP_EOL; diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/bin/execute.php b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/execute.php new file mode 100755 index 0000000..edadebb --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/execute.php @@ -0,0 +1,21 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use Fidry\CpuCoreCounter\Diagnoser; +use Fidry\CpuCoreCounter\Finder\FinderRegistry; + +require_once __DIR__.'/../vendor/autoload.php'; + +echo 'Executing finders...'.PHP_EOL.PHP_EOL; +echo Diagnoser::execute(FinderRegistry::getAllVariants()).PHP_EOL; diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/bin/trace.php b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/trace.php new file mode 100755 index 0000000..adb52e2 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/bin/trace.php @@ -0,0 +1,32 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use Fidry\CpuCoreCounter\CpuCoreCounter; +use Fidry\CpuCoreCounter\Finder\FinderRegistry; + +require_once __DIR__.'/../vendor/autoload.php'; + +$separator = str_repeat('–', 80); + +echo 'With all finders...'.PHP_EOL.PHP_EOL; +echo (new CpuCoreCounter(FinderRegistry::getAllVariants()))->trace().PHP_EOL; +echo $separator.PHP_EOL.PHP_EOL; + +echo 'Logical CPU cores finders...'.PHP_EOL.PHP_EOL; +echo (new CpuCoreCounter(FinderRegistry::getDefaultLogicalFinders()))->trace().PHP_EOL; +echo $separator.PHP_EOL.PHP_EOL; + +echo 'Physical CPU cores finders...'.PHP_EOL.PHP_EOL; +echo (new CpuCoreCounter(FinderRegistry::getDefaultPhysicalFinders()))->trace().PHP_EOL; +echo $separator.PHP_EOL.PHP_EOL; diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/composer.json b/trilhas_poo/vendor/fidry/cpu-core-counter/composer.json new file mode 100644 index 0000000..6ca8df6 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/composer.json @@ -0,0 +1,48 @@ +{ + "name": "fidry/cpu-core-counter", + "description": "Tiny utility to get the number of CPU cores.", + "license": "MIT", + "type": "library", + "keywords": [ + "cpu", + "core" + ], + "authors": [ + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry/makefile": "^0.2.0", + "fidry/php-cs-fixer-config": "^1.1.2", + "phpstan/extension-installer": "^1.2.0", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-deprecation-rules": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", + "phpunit/phpunit": "^8.5.31 || ^9.5.26", + "webmozarts/strict-phpunit": "^7.5" + }, + "autoload": { + "psr-4": { + "Fidry\\CpuCoreCounter\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Fidry\\CpuCoreCounter\\Test\\": "tests/" + } + }, + "config": { + "allow-plugins": { + "ergebnis/composer-normalize": true, + "infection/extension-installer": true, + "phpstan/extension-installer": true + }, + "sort-packages": true + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php new file mode 100644 index 0000000..d115031 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php @@ -0,0 +1,270 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter; + +use Fidry\CpuCoreCounter\Finder\CpuCoreFinder; +use Fidry\CpuCoreCounter\Finder\EnvVariableFinder; +use Fidry\CpuCoreCounter\Finder\FinderRegistry; +use InvalidArgumentException; +use function implode; +use function max; +use function sprintf; +use function sys_getloadavg; +use const PHP_EOL; + +final class CpuCoreCounter +{ + /** + * @var list + */ + private $finders; + + /** + * @var positive-int|null + */ + private $count; + + /** + * @param list|null $finders + */ + public function __construct(?array $finders = null) + { + $this->finders = $finders ?? FinderRegistry::getDefaultLogicalFinders(); + } + + /** + * @param positive-int|0 $reservedCpus Number of CPUs to reserve. This is useful when you want + * to reserve some CPUs for other processes. If the main + * process is going to be busy still, you may want to set + * this value to 1. + * @param non-zero-int|null $countLimit The maximum number of CPUs to return. If not provided, it + * may look for a limit in the environment variables, e.g. + * KUBERNETES_CPU_LIMIT. If negative, the limit will be + * the total number of cores found minus the absolute value. + * For instance if the system has 10 cores and countLimit=-2, + * then the effective limit considered will be 8. + * @param float|null $loadLimit Element of [0., 1.]. Percentage representing the + * amount of cores that should be used among the available + * resources. For instance, if set to 0.7, it will use 70% + * of the available cores, i.e. if 1 core is reserved, 11 + * cores are available and 5 are busy, it will use 70% + * of (11-1-5)=5 cores, so 3 cores. Set this parameter to null + * to skip this check. Beware that 1 does not mean "no limit", + * but 100% of the _available_ resources, i.e. with the + * previous example, it will return 5 cores. How busy is + * the system is determined by the system load average + * (see $systemLoadAverage). + * @param float|null $systemLoadAverage The system load average. If passed, it will use + * this information to limit the available cores based + * on the _available_ resources. For instance, if there + * is 10 cores but 3 are busy, then only 7 cores will + * be considered for further calculation. If set to + * `null`, it will use `sys_getloadavg()` to check the + * load of the system in the past minute. You can + * otherwise pass an arbitrary value. Should be a + * positive float. + * + * @see https://php.net/manual/en/function.sys-getloadavg.php + */ + public function getAvailableForParallelisation( + int $reservedCpus = 0, + ?int $countLimit = null, + ?float $loadLimit = null, + ?float $systemLoadAverage = 0. + ): ParallelisationResult { + self::checkCountLimit($countLimit); + self::checkLoadLimit($loadLimit); + self::checkSystemLoadAverage($systemLoadAverage); + + $totalCoreCount = $this->getCountWithFallback(1); + $availableCores = max(1, $totalCoreCount - $reservedCpus); + + // Adjust available CPUs based on current load + if (null !== $loadLimit) { + // https://github.com/phpstan/phpstan/issues/13198 + /** @var float $correctedSystemLoadAverage */ + $correctedSystemLoadAverage = null === $systemLoadAverage + ? sys_getloadavg()[0] ?? 0. + : $systemLoadAverage; + + $availableCores = max( + 1, + $loadLimit * ($availableCores - $correctedSystemLoadAverage) + ); + } + + if (null === $countLimit) { + $correctedCountLimit = self::getKubernetesLimit(); + } else { + $correctedCountLimit = $countLimit > 0 + ? $countLimit + : max(1, $totalCoreCount + $countLimit); + } + + if (null !== $correctedCountLimit && $availableCores > $correctedCountLimit) { + $availableCores = $correctedCountLimit; + } + + return new ParallelisationResult( + $reservedCpus, + $countLimit, + $loadLimit, + $systemLoadAverage, + $correctedCountLimit, + $correctedSystemLoadAverage ?? $systemLoadAverage, + $totalCoreCount, + (int) $availableCores + ); + } + + /** + * @throws NumberOfCpuCoreNotFound + * + * @return positive-int + */ + public function getCount(): int + { + // Memoize result + if (null === $this->count) { + $this->count = $this->findCount(); + } + + return $this->count; + } + + /** + * @param positive-int $fallback + * + * @return positive-int + */ + public function getCountWithFallback(int $fallback): int + { + try { + return $this->getCount(); + } catch (NumberOfCpuCoreNotFound $exception) { + return $fallback; + } + } + + /** + * This method is mostly for debugging purposes. + */ + public function trace(): string + { + $output = []; + + foreach ($this->finders as $finder) { + $output[] = sprintf( + 'Executing the finder "%s":', + $finder->toString() + ); + $output[] = $finder->diagnose(); + + $cores = $finder->find(); + + if (null !== $cores) { + $output[] = 'Result found: '.$cores; + + break; + } + + $output[] = '–––'; + } + + return implode(PHP_EOL, $output); + } + + /** + * @throws NumberOfCpuCoreNotFound + * + * @return positive-int + */ + private function findCount(): int + { + foreach ($this->finders as $finder) { + $cores = $finder->find(); + + if (null !== $cores) { + return $cores; + } + } + + throw NumberOfCpuCoreNotFound::create(); + } + + /** + * @throws NumberOfCpuCoreNotFound + * + * @return array{CpuCoreFinder, positive-int} + */ + public function getFinderAndCores(): array + { + foreach ($this->finders as $finder) { + $cores = $finder->find(); + + if (null !== $cores) { + return [$finder, $cores]; + } + } + + throw NumberOfCpuCoreNotFound::create(); + } + + /** + * @return positive-int|null + */ + public static function getKubernetesLimit(): ?int + { + $finder = new EnvVariableFinder('KUBERNETES_CPU_LIMIT'); + + return $finder->find(); + } + + private static function checkCountLimit(?int $countLimit): void + { + if (0 === $countLimit) { + throw new InvalidArgumentException( + 'The count limit must be a non zero integer. Got "0".' + ); + } + } + + private static function checkLoadLimit(?float $loadLimit): void + { + if (null === $loadLimit) { + return; + } + + if ($loadLimit < 0. || $loadLimit > 1.) { + throw new InvalidArgumentException( + sprintf( + 'The load limit must be in the range [0., 1.], got "%s".', + $loadLimit + ) + ); + } + } + + private static function checkSystemLoadAverage(?float $systemLoadAverage): void + { + if (null !== $systemLoadAverage && $systemLoadAverage < 0.) { + throw new InvalidArgumentException( + sprintf( + 'The system load average must be a positive float, got "%s".', + $systemLoadAverage + ) + ); + } + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Diagnoser.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Diagnoser.php new file mode 100644 index 0000000..872b55f --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Diagnoser.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter; + +use Fidry\CpuCoreCounter\Finder\CpuCoreFinder; +use function array_map; +use function explode; +use function implode; +use function max; +use function str_repeat; +use const PHP_EOL; + +/** + * Utility to debug. + * + * @private + */ +final class Diagnoser +{ + /** + * Provides an aggregated diagnosis based on each finders diagnosis. + * + * @param list $finders + */ + public static function diagnose(array $finders): string + { + $diagnoses = array_map( + static function (CpuCoreFinder $finder): string { + return self::diagnoseFinder($finder); + }, + $finders + ); + + return implode(PHP_EOL, $diagnoses); + } + + /** + * Executes each finders. + * + * @param list $finders + */ + public static function execute(array $finders): string + { + $diagnoses = array_map( + static function (CpuCoreFinder $finder): string { + $coresCount = $finder->find(); + + return implode( + '', + [ + $finder->toString(), + ': ', + null === $coresCount ? 'NULL' : $coresCount, + ] + ); + }, + $finders + ); + + return implode(PHP_EOL, $diagnoses); + } + + private static function diagnoseFinder(CpuCoreFinder $finder): string + { + $diagnosis = $finder->diagnose(); + + $maxLineLength = max( + array_map( + 'strlen', + explode(PHP_EOL, $diagnosis) + ) + ); + + $separator = str_repeat('-', $maxLineLength); + + return implode( + '', + [ + $finder->toString().':'.PHP_EOL, + $separator.PHP_EOL, + $diagnosis.PHP_EOL, + $separator.PHP_EOL, + ] + ); + } + + private function __construct() + { + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php new file mode 100644 index 0000000..d526ce1 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Executor; + +use function fclose; +use function function_exists; +use function is_resource; +use function proc_close; +use function proc_open; +use function stream_get_contents; + +final class ProcOpenExecutor implements ProcessExecutor +{ + public function execute(string $command): ?array + { + if (!function_exists('proc_open')) { + return null; + } + + $pipes = []; + + $process = @proc_open( + $command, + [ + ['pipe', 'rb'], + ['pipe', 'wb'], // stdout + ['pipe', 'wb'], // stderr + ], + $pipes + ); + // https://github.com/phpstan/phpstan/issues/13197 + /** @var array{resource, resource, resource} $pipes */ + if (!is_resource($process)) { + return null; + } + + fclose($pipes[0]); + + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + + proc_close($process); + + return [$stdout, $stderr]; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php new file mode 100644 index 0000000..287c01e --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Executor; + +interface ProcessExecutor +{ + /** + * @return array{string, string}|null STDOUT & STDERR tuple + */ + public function execute(string $command): ?array; +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletLogicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletLogicalFinder.php new file mode 100644 index 0000000..4065064 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletLogicalFinder.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function preg_match; + +/** + * Find the number of logical CPU cores for Windows leveraging the Get-CimInstance + * cmdlet, which is a newer version that is recommended over Get-WmiObject. + */ +final class CmiCmdletLogicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfLogicalProcessors[\s\n]-+[\s\n]+(?\d+)/'; + + protected function getCommand(): string + { + return 'Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -Property NumberOfLogicalProcessors'; + } + + public function toString(): string + { + return 'CmiCmdletLogicalFinder'; + } + + protected function countCpuCores(string $process): ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + + /** @phpstan-ignore offsetAccess.notFound */ + $count = $matches['count']; + + return parent::countCpuCores($count); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletPhysicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletPhysicalFinder.php new file mode 100644 index 0000000..4559021 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CmiCmdletPhysicalFinder.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function preg_match; + +/** + * Find the number of physical CPU cores for Windows. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L912-L916 + */ +final class CmiCmdletPhysicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfCores[\s\n]-+[\s\n]+(?\d+)/'; + + protected function getCommand(): string + { + return 'Get-CimInstance -ClassName Win32_Processor | Select-Object -Property NumberOfCores'; + } + + public function toString(): string + { + return 'CmiCmdletPhysicalFinder'; + } + + protected function countCpuCores(string $process): ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + + /** @phpstan-ignore offsetAccess.notFound */ + $count = $matches['count']; + + return parent::countCpuCores($count); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php new file mode 100644 index 0000000..edb40e8 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +interface CpuCoreFinder +{ + /** + * Provides an explanation which may offer some insight as to what the finder + * will be able to find. + * + * This is practical to have an idea of what each finder will find collect + * information for the unit tests, since integration tests are quite complicated + * as dependent on complex infrastructures. + */ + public function diagnose(): string; + + /** + * Find the number of CPU cores. If it could not find it, returns null. The + * means used to find the cores are at the implementation discretion. + * + * @return positive-int|null + */ + public function find(): ?int; + + public function toString(): string; +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php new file mode 100644 index 0000000..8013877 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function file_get_contents; +use function is_file; +use function sprintf; +use function substr_count; +use const PHP_EOL; + +/** + * Find the number of CPU cores looking up at the cpuinfo file which is available + * on Linux systems and Windows systems with a Linux sub-system. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://unix.stackexchange.com/questions/146051/number-of-processors-in-proc-cpuinfo + */ +final class CpuInfoFinder implements CpuCoreFinder +{ + private const CPU_INFO_PATH = '/proc/cpuinfo'; + + public function diagnose(): string + { + if (!is_file(self::CPU_INFO_PATH)) { + return sprintf( + 'The file "%s" could not be found.', + self::CPU_INFO_PATH + ); + } + + $cpuInfo = file_get_contents(self::CPU_INFO_PATH); + + if (false === $cpuInfo) { + return sprintf( + 'Could not get the content of the file "%s".', + self::CPU_INFO_PATH + ); + } + + return sprintf( + 'Found the file "%s" with the content:%s%s%sWill return "%s".', + self::CPU_INFO_PATH, + PHP_EOL, + $cpuInfo, + PHP_EOL, + self::countCpuCores($cpuInfo) + ); + } + + /** + * @return positive-int|null + */ + public function find(): ?int + { + $cpuInfo = self::getCpuInfo(); + + return null === $cpuInfo ? null : self::countCpuCores($cpuInfo); + } + + public function toString(): string + { + return 'CpuInfoFinder'; + } + + private static function getCpuInfo(): ?string + { + if (!@is_file(self::CPU_INFO_PATH)) { + return null; + } + + $cpuInfo = @file_get_contents(self::CPU_INFO_PATH); + + return false === $cpuInfo + ? null + : $cpuInfo; + } + + /** + * @internal + * + * @return positive-int|null + */ + public static function countCpuCores(string $cpuInfo): ?int + { + $processorCount = substr_count($cpuInfo, 'processor'); + + return $processorCount > 0 ? $processorCount : null; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php new file mode 100644 index 0000000..8c99612 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function sprintf; + +/** + * This finder returns whatever value you gave to it. This is useful for testing + * or as a fallback to avoid to catch the NumberOfCpuCoreNotFound exception. + */ +final class DummyCpuCoreFinder implements CpuCoreFinder +{ + /** + * @var positive-int + */ + private $count; + + public function diagnose(): string + { + return sprintf( + 'Will return "%d".', + $this->count + ); + } + + /** + * @param positive-int $count + */ + public function __construct(int $count) + { + $this->count = $count; + } + + /** @phpstan-ignore return.unusedType */ + public function find(): ?int + { + return $this->count; + } + + public function toString(): string + { + return sprintf( + 'DummyCpuCoreFinder(value=%d)', + $this->count + ); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/EnvVariableFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/EnvVariableFinder.php new file mode 100644 index 0000000..52d0411 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/EnvVariableFinder.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function getenv; +use function preg_match; +use function sprintf; +use function var_export; + +final class EnvVariableFinder implements CpuCoreFinder +{ + /** @var string */ + private $environmentVariableName; + + public function __construct(string $environmentVariableName) + { + $this->environmentVariableName = $environmentVariableName; + } + + public function diagnose(): string + { + $value = getenv($this->environmentVariableName); + + return sprintf( + 'parse(getenv(%s)=%s)=%s', + $this->environmentVariableName, + var_export($value, true), + self::isPositiveInteger($value) ? $value : 'null' + ); + } + + public function find(): ?int + { + $value = getenv($this->environmentVariableName); + + if (is_string($value) && 1 === preg_match('/^(\d+)m$/', $value, $matches)) { + $millicores = $matches[1]; + $value = (string) floor($millicores / 1000); + } + + return self::isPositiveInteger($value) + ? (int) $value + : null; + } + + public function toString(): string + { + return sprintf( + 'getenv(%s)', + $this->environmentVariableName + ); + } + + /** + * @param string|false $value + */ + private static function isPositiveInteger($value): bool + { + return false !== $value + && 1 === preg_match('/^\d+$/', $value) + && (int) $value > 0; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php new file mode 100644 index 0000000..ca9b860 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +final class FinderRegistry +{ + /** + * @return list List of all the known finders with all their variants. + */ + public static function getAllVariants(): array + { + return [ + new CpuInfoFinder(), + new DummyCpuCoreFinder(1), + new HwLogicalFinder(), + new HwPhysicalFinder(), + new LscpuLogicalFinder(), + new LscpuPhysicalFinder(), + new _NProcessorFinder(), + new NProcessorFinder(), + new NProcFinder(true), + new NProcFinder(false), + new NullCpuCoreFinder(), + SkipOnOSFamilyFinder::forWindows( + new DummyCpuCoreFinder(1) + ), + OnlyOnOSFamilyFinder::forWindows( + new DummyCpuCoreFinder(1) + ), + new OnlyInPowerShellFinder(new CmiCmdletLogicalFinder()), + new OnlyInPowerShellFinder(new CmiCmdletPhysicalFinder()), + new WindowsRegistryLogicalFinder(), + new WmicPhysicalFinder(), + new WmicLogicalFinder(), + ]; + } + + /** + * @return list + */ + public static function getDefaultLogicalFinders(): array + { + return [ + OnlyOnOSFamilyFinder::forWindows( + new OnlyInPowerShellFinder( + new CmiCmdletLogicalFinder() + ) + ), + OnlyOnOSFamilyFinder::forWindows(new WindowsRegistryLogicalFinder()), + OnlyOnOSFamilyFinder::forWindows(new WmicLogicalFinder()), + new NProcFinder(), + new HwLogicalFinder(), + new _NProcessorFinder(), + new NProcessorFinder(), + new LscpuLogicalFinder(), + new CpuInfoFinder(), + ]; + } + + /** + * @return list + */ + public static function getDefaultPhysicalFinders(): array + { + return [ + OnlyOnOSFamilyFinder::forWindows( + new OnlyInPowerShellFinder( + new CmiCmdletPhysicalFinder() + ) + ), + OnlyOnOSFamilyFinder::forWindows(new WmicPhysicalFinder()), + new HwPhysicalFinder(), + new LscpuPhysicalFinder(), + ]; + } + + private function __construct() + { + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php new file mode 100644 index 0000000..d112903 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for Linux, BSD and OSX. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://opensource.apple.com/source/xnu/xnu-792.2.4/libkern/libkern/sysctl.h.auto.html + */ +final class HwLogicalFinder extends ProcOpenBasedFinder +{ + protected function getCommand(): string + { + return 'sysctl -n hw.logicalcpu'; + } + + public function toString(): string + { + return 'HwLogicalFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php new file mode 100644 index 0000000..65ca1cf --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of physical CPU cores for Linux, BSD and OSX. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://opensource.apple.com/source/xnu/xnu-792.2.4/libkern/libkern/sysctl.h.auto.html + */ +final class HwPhysicalFinder extends ProcOpenBasedFinder +{ + protected function getCommand(): string + { + return 'sysctl -n hw.physicalcpu'; + } + + public function toString(): string + { + return 'HwPhysicalFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php new file mode 100644 index 0000000..bce09eb --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function count; +use function explode; +use function is_array; +use function preg_grep; +use const PHP_EOL; + +/** + * The number of logical cores. + * + * @see https://stackoverflow.com/a/23378780/5846754 + */ +final class LscpuLogicalFinder extends ProcOpenBasedFinder +{ + public function getCommand(): string + { + return 'lscpu -p'; + } + + protected function countCpuCores(string $process): ?int + { + $lines = explode(PHP_EOL, $process); + $actualLines = preg_grep('/^\d+,/', $lines); + + if (!is_array($actualLines)) { + return null; + } + + $count = count($actualLines); + + return 0 === $count ? null : $count; + } + + public function toString(): string + { + return 'LscpuLogicalFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php new file mode 100644 index 0000000..c89bcb9 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function count; +use function explode; +use function is_array; +use function preg_grep; +use function strtok; +use const PHP_EOL; + +/** + * The number of physical processors. + * + * @see https://stackoverflow.com/a/23378780/5846754 + */ +final class LscpuPhysicalFinder extends ProcOpenBasedFinder +{ + public function toString(): string + { + return 'LscpuPhysicalFinder'; + } + + public function getCommand(): string + { + return 'lscpu -p'; + } + + protected function countCpuCores(string $process): ?int + { + $lines = explode(PHP_EOL, $process); + /** @var string[]|false $actualLines */ + $actualLines = preg_grep('/^\d+/', $lines); + + if (!is_array($actualLines)) { + return null; + } + + $cores = []; + foreach ($actualLines as $line) { + strtok($line, ','); + $core = strtok(','); + + if (false === $core) { + continue; + } + + $cores[$core] = true; + } + unset($cores['-']); + + $count = count($cores); + + return 0 === $count ? null : $count; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php new file mode 100644 index 0000000..c0f7a6f --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use Fidry\CpuCoreCounter\Executor\ProcessExecutor; +use function sprintf; + +/** + * The number of (logical) cores. + * + * @see https://github.com/infection/infection/blob/fbd8c44/src/Resource/Processor/CpuCoresCountProvider.php#L69-L82 + * @see https://unix.stackexchange.com/questions/146051/number-of-processors-in-proc-cpuinfo + */ +final class NProcFinder extends ProcOpenBasedFinder +{ + /** + * @var bool + */ + private $all; + + /** + * @param bool $all If disabled will give the number of cores available for the current process + * only. This is disabled by default as it is known to be "buggy" on virtual + * environments as the virtualization tool, e.g. VMWare, might over-commit + * resources by default. + */ + public function __construct( + bool $all = false, + ?ProcessExecutor $executor = null + ) { + parent::__construct($executor); + + $this->all = $all; + } + + public function toString(): string + { + return sprintf( + 'NProcFinder(all=%s)', + $this->all ? 'true' : 'false' + ); + } + + protected function getCommand(): string + { + return 'nproc'.($this->all ? ' --all' : ''); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php new file mode 100644 index 0000000..9143e31 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for FreeSBD, Solaris and the likes. + * + * @see https://twitter.com/freebsdfrau/status/1052016199452700678?s=20&t=M2pHkRqmmna-UF68lfL2hw + */ +final class NProcessorFinder extends ProcOpenBasedFinder +{ + protected function getCommand(): string + { + return 'getconf NPROCESSORS_ONLN'; + } + + public function toString(): string + { + return 'NProcessorFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php new file mode 100644 index 0000000..50af2d4 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +/** + * This finder returns whatever value you gave to it. This is useful for testing. + */ +final class NullCpuCoreFinder implements CpuCoreFinder +{ + public function diagnose(): string + { + return 'Will return "null".'; + } + + public function find(): ?int + { + return null; + } + + public function toString(): string + { + return 'NullCpuCoreFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyInPowerShellFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyInPowerShellFinder.php new file mode 100644 index 0000000..d36d030 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyInPowerShellFinder.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function getenv; +use function sprintf; + +final class OnlyInPowerShellFinder implements CpuCoreFinder +{ + /** + * @var CpuCoreFinder + */ + private $decoratedFinder; + + public function __construct(CpuCoreFinder $decoratedFinder) + { + $this->decoratedFinder = $decoratedFinder; + } + + public function diagnose(): string + { + $powerShellModulePath = getenv('PSModulePath'); + + return $this->skip() + ? sprintf( + 'Skipped; no power shell module path detected ("%s").', + $powerShellModulePath + ) + : $this->decoratedFinder->diagnose(); + } + + public function find(): ?int + { + return $this->skip() + ? null + : $this->decoratedFinder->find(); + } + + public function toString(): string + { + return sprintf( + 'OnlyInPowerShellFinder(%s)', + $this->decoratedFinder->toString() + ); + } + + private function skip(): bool + { + return false === getenv('PSModulePath'); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php new file mode 100644 index 0000000..3147808 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function implode; +use function sprintf; +use const PHP_OS_FAMILY; + +final class OnlyOnOSFamilyFinder implements CpuCoreFinder +{ + /** + * @var list + */ + private $skippedOSFamilies; + + /** + * @var CpuCoreFinder + */ + private $decoratedFinder; + + /** + * @param string|list $skippedOSFamilyOrFamilies + */ + public function __construct( + $skippedOSFamilyOrFamilies, + CpuCoreFinder $decoratedFinder + ) { + $this->skippedOSFamilies = (array) $skippedOSFamilyOrFamilies; + $this->decoratedFinder = $decoratedFinder; + } + + public static function forWindows(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Windows', + $decoratedFinder + ); + } + + public static function forBSD(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'BSD', + $decoratedFinder + ); + } + + public static function forDarwin(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Darwin', + $decoratedFinder + ); + } + + public static function forSolaris(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Solaris', + $decoratedFinder + ); + } + + public static function forLinux(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Linux', + $decoratedFinder + ); + } + + public function diagnose(): string + { + return $this->skip() + ? sprintf( + 'Skipped platform detected ("%s").', + PHP_OS_FAMILY + ) + : $this->decoratedFinder->diagnose(); + } + + public function find(): ?int + { + return $this->skip() + ? null + : $this->decoratedFinder->find(); + } + + public function toString(): string + { + return sprintf( + 'OnlyOnOSFamilyFinder(only=(%s),%s)', + implode(',', $this->skippedOSFamilies), + $this->decoratedFinder->toString() + ); + } + + private function skip(): bool + { + return !in_array(PHP_OS_FAMILY, $this->skippedOSFamilies, true); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php new file mode 100644 index 0000000..4d51f89 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php @@ -0,0 +1,107 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use Fidry\CpuCoreCounter\Executor\ProcessExecutor; +use Fidry\CpuCoreCounter\Executor\ProcOpenExecutor; +use function filter_var; +use function function_exists; +use function is_int; +use function sprintf; +use function trim; +use const FILTER_VALIDATE_INT; +use const PHP_EOL; + +abstract class ProcOpenBasedFinder implements CpuCoreFinder +{ + /** + * @var ProcessExecutor + */ + private $executor; + + public function __construct(?ProcessExecutor $executor = null) + { + $this->executor = $executor ?? new ProcOpenExecutor(); + } + + public function diagnose(): string + { + if (!function_exists('proc_open')) { + return 'The function "proc_open" is not available.'; + } + + $command = $this->getCommand(); + $output = $this->executor->execute($command); + + if (null === $output) { + return sprintf( + 'Failed to execute the command "%s".', + $command + ); + } + + [$stdout, $stderr] = $output; + $failed = '' !== trim($stderr); + + return $failed + ? sprintf( + 'Executed the command "%s" which wrote the following output to the STDERR:%s%s%sWill return "null".', + $command, + PHP_EOL, + $stderr, + PHP_EOL + ) + : sprintf( + 'Executed the command "%s" and got the following (STDOUT) output:%s%s%sWill return "%s".', + $command, + PHP_EOL, + $stdout, + PHP_EOL, + $this->countCpuCores($stdout) ?? 'null' + ); + } + + /** + * @return positive-int|null + */ + public function find(): ?int + { + $output = $this->executor->execute($this->getCommand()); + + if (null === $output) { + return null; + } + + [$stdout, $stderr] = $output; + $failed = '' !== trim($stderr); + + return $failed + ? null + : $this->countCpuCores($stdout); + } + + /** + * @internal + * + * @return positive-int|null + */ + protected function countCpuCores(string $process): ?int + { + $cpuCount = filter_var($process, FILTER_VALIDATE_INT); + + return is_int($cpuCount) && $cpuCount > 0 ? $cpuCount : null; + } + + abstract protected function getCommand(): string; +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php new file mode 100644 index 0000000..66a5016 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function implode; +use function in_array; +use function sprintf; + +final class SkipOnOSFamilyFinder implements CpuCoreFinder +{ + /** + * @var list + */ + private $skippedOSFamilies; + + /** + * @var CpuCoreFinder + */ + private $decoratedFinder; + + /** + * @param string|list $skippedOSFamilyOrFamilies + */ + public function __construct( + $skippedOSFamilyOrFamilies, + CpuCoreFinder $decoratedFinder + ) { + $this->skippedOSFamilies = (array) $skippedOSFamilyOrFamilies; + $this->decoratedFinder = $decoratedFinder; + } + + public static function forWindows(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Windows', + $decoratedFinder + ); + } + + public static function forBSD(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'BSD', + $decoratedFinder + ); + } + + public static function forDarwin(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Darwin', + $decoratedFinder + ); + } + + public static function forSolaris(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Solaris', + $decoratedFinder + ); + } + + public static function forLinux(CpuCoreFinder $decoratedFinder): self + { + return new self( + 'Linux', + $decoratedFinder + ); + } + + public function diagnose(): string + { + return $this->skip() + ? sprintf( + 'Skipped platform detected ("%s").', + PHP_OS_FAMILY + ) + : $this->decoratedFinder->diagnose(); + } + + public function find(): ?int + { + return $this->skip() + ? null + : $this->decoratedFinder->find(); + } + + public function toString(): string + { + return sprintf( + 'SkipOnOSFamilyFinder(skip=(%s),%s)', + implode(',', $this->skippedOSFamilies), + $this->decoratedFinder->toString() + ); + } + + private function skip(): bool + { + return in_array(PHP_OS_FAMILY, $this->skippedOSFamilies, true); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WindowsRegistryLogicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WindowsRegistryLogicalFinder.php new file mode 100644 index 0000000..b223652 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WindowsRegistryLogicalFinder.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function array_filter; +use function count; +use function explode; +use const PHP_EOL; + +/** + * Find the number of logical CPU cores for Windows. + * + * @see https://knowledge.informatica.com/s/article/151521 + */ +final class WindowsRegistryLogicalFinder extends ProcOpenBasedFinder +{ + protected function getCommand(): string + { + return 'reg query HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor'; + } + + public function toString(): string + { + return 'WindowsRegistryLogicalFinder'; + } + + protected function countCpuCores(string $process): ?int + { + $count = count( + array_filter( + explode(PHP_EOL, $process), + static function (string $line): bool { + return '' !== trim($line); + } + ) + ); + + return $count > 0 ? $count : null; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php new file mode 100644 index 0000000..0beb21e --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function preg_match; + +/** + * Find the number of logical CPU cores for Windows. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L912-L916 + */ +final class WmicLogicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfLogicalProcessors[\s\n]+(?\d+)/'; + + protected function getCommand(): string + { + return 'wmic cpu get NumberOfLogicalProcessors'; + } + + public function toString(): string + { + return 'WmicLogicalFinder'; + } + + protected function countCpuCores(string $process): ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + + /** @phpstan-ignore offsetAccess.notFound */ + $count = $matches['count']; + + return parent::countCpuCores($count); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php new file mode 100644 index 0000000..04abdc5 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +use function preg_match; + +/** + * Find the number of physical CPU cores for Windows. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L912-L916 + */ +final class WmicPhysicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfCores[\s\n]+(?\d+)/'; + + protected function getCommand(): string + { + return 'wmic cpu get NumberOfCores'; + } + + public function toString(): string + { + return 'WmicPhysicalFinder'; + } + + protected function countCpuCores(string $process): ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + + /** @phpstan-ignore offsetAccess.notFound */ + $count = $matches['count']; + + return parent::countCpuCores($count); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php new file mode 100644 index 0000000..23f452e --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for Linux and the likes. + * + * @see https://twitter.com/freebsdfrau/status/1052016199452700678?s=20&t=M2pHkRqmmna-UF68lfL2hw + */ +final class _NProcessorFinder extends ProcOpenBasedFinder +{ + protected function getCommand(): string + { + return 'getconf _NPROCESSORS_ONLN'; + } + + public function toString(): string + { + return '_NProcessorFinder'; + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php new file mode 100644 index 0000000..e54f893 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter; + +use RuntimeException; + +final class NumberOfCpuCoreNotFound extends RuntimeException +{ + public static function create(): self + { + return new self( + 'Could not find the number of CPU cores available.' + ); + } +} diff --git a/trilhas_poo/vendor/fidry/cpu-core-counter/src/ParallelisationResult.php b/trilhas_poo/vendor/fidry/cpu-core-counter/src/ParallelisationResult.php new file mode 100644 index 0000000..1f29434 --- /dev/null +++ b/trilhas_poo/vendor/fidry/cpu-core-counter/src/ParallelisationResult.php @@ -0,0 +1,87 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Fidry\CpuCoreCounter; + +/** + * @readonly + */ +final class ParallelisationResult +{ + /** + * @var positive-int|0 + */ + public $passedReservedCpus; + + /** + * @var non-zero-int|null + */ + public $passedCountLimit; + + /** + * @var float|null + */ + public $passedLoadLimit; + + /** + * @var float|null + */ + public $passedSystemLoadAverage; + + /** + * @var non-zero-int|null + */ + public $correctedCountLimit; + + /** + * @var float|null + */ + public $correctedSystemLoadAverage; + + /** + * @var positive-int + */ + public $totalCoresCount; + + /** + * @var positive-int + */ + public $availableCpus; + + /** + * @param positive-int|0 $passedReservedCpus + * @param non-zero-int|null $passedCountLimit + * @param non-zero-int|null $correctedCountLimit + * @param positive-int $totalCoresCount + * @param positive-int $availableCpus + */ + public function __construct( + int $passedReservedCpus, + ?int $passedCountLimit, + ?float $passedLoadLimit, + ?float $passedSystemLoadAverage, + ?int $correctedCountLimit, + ?float $correctedSystemLoadAverage, + int $totalCoresCount, + int $availableCpus + ) { + $this->passedReservedCpus = $passedReservedCpus; + $this->passedCountLimit = $passedCountLimit; + $this->passedLoadLimit = $passedLoadLimit; + $this->passedSystemLoadAverage = $passedSystemLoadAverage; + $this->correctedCountLimit = $correctedCountLimit; + $this->correctedSystemLoadAverage = $correctedSystemLoadAverage; + $this->totalCoresCount = $totalCoresCount; + $this->availableCpus = $availableCpus; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/LICENSE b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/LICENSE new file mode 100644 index 0000000..871def0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012+ Fabien Potencier, Dariusz Rumiński + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/README.md b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/README.md new file mode 100644 index 0000000..c5a5df8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/README.md @@ -0,0 +1,97 @@ +

+ + PHP CS Fixer logo + +

+ +# PHP Coding Standards Fixer + +The PHP Coding Standards Fixer (PHP CS Fixer) fixes your code to follow the standards. + +If you are already using a linter to identify coding standards problems in your +code, you know that fixing them by hand is tedious, especially on large +projects. This tool not only detects them, but also fixes them for you. + +PHP CS Fixer has built-in rule sets, whether you want to follow PHP coding standards as defined by [PHP-FIG's PER Coding Style](https://www.php-fig.org/per/coding-style/) - [`@PER-CS`](./doc/ruleSets/PER-CS.rst), +a wide community like the [Symfony](https://symfony.com/doc/current/contributing/code/standards.html) - [`@Symfony`](./doc/ruleSets/Symfony.rst), +or our opinionated one - [@PhpCsFixer](./doc/ruleSets/PhpCsFixer.rst). +You can also define your (team's) style through the [configuration file](./doc/config.rst). + +PHP CS Fixer can not only unify the style of your code, but also help to modernise your codebase towards +newer PHP (e.g. [`@autoPHPMigration`](./doc/ruleSets/AutoPHPMigration.rst) and [`@autoPHPMigration:risky`](./doc/ruleSets/AutoPHPMigrationRisky.rst)) and newer PHPUnit (e.g. [`@autoPHPUnitMigration:risky`](./doc/ruleSets/AutoPHPUnitMigrationRisky.rst)). + +There are also [`@auto`](./doc/ruleSets/Auto.rst) and [`@auto:risky`](./doc/ruleSets/AutoRisky.rst) that aim to provide good base rules. + +## Supported PHP Versions + +* PHP 7.4 - PHP 8.5 + +> [!NOTE] +> Each new PHP version requires a huge effort to support the new syntax. +> That's why the latest PHP version might not be supported yet. If you need it, +> please consider supporting the project in any convenient way, for example, +> with code contributions or reviewing existing PRs. To run PHP CS Fixer on yet +> unsupported versions "at your own risk" - use `--allow-unsupported-php-version=yes` option. + +## Documentation + +### Installation + +The recommended way to install PHP CS Fixer is to use [Composer](https://getcomposer.org/download/): + +```sh +composer require --dev friendsofphp/php-cs-fixer +## or when facing conflicts in dependencies: +composer require --dev php-cs-fixer/shim +``` + +For more details and other installation methods (also with Docker or behind CI), see +[installation instructions](./doc/installation.rst). + +### Usage + +Assuming you installed PHP CS Fixer as instructed above, you can +initialise base config for your project by using following command: + +```sh +./vendor/bin/php-cs-fixer init +``` + +To automatically fix your project, or only check against the need of changes, run: + +```sh +./vendor/bin/php-cs-fixer fix +./vendor/bin/php-cs-fixer check +``` + +See [usage](./doc/usage.rst), list of [built-in rules](./doc/rules/index.rst), list of [rule sets](./doc/ruleSets/index.rst) +and [configuration file](./doc/config.rst) documentation for more details. + +If you need to apply code styles that are not built-in into the tool, you can +[create custom rules](./doc/custom_rules.rst). + +## Editor Integration + +Native support exists for: + +* [PhpStorm](https://www.jetbrains.com/help/phpstorm/using-php-cs-fixer.html) + +Community plugins exist for: + +* [NetBeans](https://plugins.netbeans.apache.org/catalogue/?id=36) +* [Sublime Text](https://github.com/benmatselby/sublime-phpcs) +* [Vim](https://github.com/stephpy/vim-php-cs-fixer) +* [VS Code](https://github.com/junstyle/vscode-php-cs-fixer) + +## Community + +The PHP CS Fixer is maintained on GitHub at . +Contributions, bug reports and ideas about new features are welcome there. + +You can reach us in the [GitHub Discussions](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/) regarding the +project, configuration, possible improvements, ideas and questions. + +## Contribute + +The tool comes with quite a few built-in fixers, but everyone is more than +welcome to [contribute](./CONTRIBUTING.md) more of them. diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/composer.json b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/composer.json new file mode 100644 index 0000000..7e59768 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/composer.json @@ -0,0 +1,220 @@ +{ + "name": "friendsofphp/php-cs-fixer", + "description": "A tool to automatically fix PHP code style", + "license": "MIT", + "type": "application", + "keywords": [ + "fixer", + "standards", + "static analysis", + "static code analysis" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "ext-filter": "*", + "ext-hash": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "clue/ndjson-react": "^1.3", + "composer/semver": "^3.4", + "composer/xdebug-handler": "^3.0.5", + "ergebnis/agent-detector": "^1.2", + "fidry/cpu-core-counter": "^1.3", + "react/child-process": "^0.6.6", + "react/event-loop": "^1.5", + "react/socket": "^1.16", + "react/stream": "^1.4", + "sebastian/diff": "^4.0.6 || ^5.1.1 || ^6.0.2 || ^7.0 || ^8.0 || ^9.0", + "symfony/console": "^5.4.47 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/event-dispatcher": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/filesystem": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/finder": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/options-resolver": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0", + "symfony/polyfill-mbstring": "^1.37", + "symfony/polyfill-php80": "^1.37", + "symfony/polyfill-php81": "^1.37", + "symfony/polyfill-php84": "^1.37", + "symfony/process": "^5.4.47 || ^6.4.24 || ^7.2 || ^8.0", + "symfony/stopwatch": "^5.4.45 || ^6.4.24 || ^7.0 || ^8.0" + }, + "require-dev": { + "facile-it/paraunit": "^1.3.1 || ^2.11.0", + "infection/infection": "^0.32.7", + "justinrainbow/json-schema": "^6.10.0", + "keradus/cli-executor": "^2.3", + "mikey179/vfsstream": "^1.6.12", + "php-coveralls/php-coveralls": "^2.9.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.8", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.8", + "phpunit/phpunit": "^9.6.35 || ^10.5.64 || ^11.5.56 || ^12.5.31", + "symfony/polyfill-php85": "^1.38", + "symfony/var-dumper": "^5.4.48 || ^6.4.36 || ^7.4.8 || ^8.1.0", + "symfony/yaml": "^5.4.53 || ^6.4.41 || ^7.4.13 || ^8.1.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + }, + "exclude-from-classmap": [ + "src/**/Internal/" + ] + }, + "autoload-dev": { + "psr-4": { + "PhpCsFixer\\PHPStan\\": "dev-tools/phpstan/src/", + "PhpCsFixer\\Tests\\": "tests/" + }, + "exclude-from-classmap": [ + "tests/Fixtures/" + ] + }, + "bin": [ + "php-cs-fixer" + ], + "config": { + "allow-plugins": { + "ergebnis/composer-normalize": true, + "infection/extension-installer": false + }, + "prefer-stable": true, + "sort-packages": true + }, + "scripts": { + "post-autoload-dump": [ + "@install-tools" + ], + "analyse-deps": "@php dev-tools/vendor/bin/composer-dependency-analyser", + "auto-review": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/bin/paraunit run --testsuite auto-review" + ], + "cs:check": "@php php-cs-fixer check --verbose --diff", + "cs:fix": "@php php-cs-fixer fix", + "cs:fix:parallel": [ + "echo '⚠️ This script is deprecated! Utilise built-in parallelisation instead.';", + "@cs:fix" + ], + "docs": "@php dev-tools/php-cs-fixer-internal docs", + "infection": "@test:mutation", + "install-tools": [ + "./dev-tools/install.sh", + "@composer install --working-dir=dev-tools" + ], + "internal": "@php dev-tools/php-cs-fixer-internal", + "mess-detector": "@php dev-tools/vendor/bin/phpmd . ansi dev-tools/mess-detector/phpmd.xml --exclude vendor/*,dev-tools/vendor/*,dev-tools/phpstan/*,tests/Fixtures/*", + "normalize": [ + "@composer normalize --working-dir=dev-tools --dry-run ../composer.json", + "@composer normalize --working-dir=dev-tools --dry-run composer.json" + ], + "normalize:fix": [ + "@composer normalize --working-dir=dev-tools ../composer.json", + "@composer normalize --working-dir=dev-tools composer.json" + ], + "php-compatibility": "@php dev-tools/vendor/bin/phpcs -p --standard=dev-tools/php-compatibility/phpcs-php-compatibility.xml", + "phpstan": "@php -d memory_limit=512M dev-tools/vendor/bin/phpstan analyse", + "phpstan:baseline": [ + "@php -d memory_limit=512M dev-tools/vendor/bin/phpstan analyse --generate-baseline=./dev-tools/phpstan/baseline/_loader.php", + "@php dev-tools/vendor/bin/split-phpstan-baseline ./dev-tools/phpstan/baseline/_loader.php --no-error-count" + ], + "qa": "@quality-assurance", + "quality-assurance": [ + "Composer\\Config::disableProcessTimeout", + "@install-tools --quiet", + "@self-check", + "@static-analysis", + "@test" + ], + "sa": "@static-analysis", + "self-check": [ + "./dev-tools/check_file_permissions.sh", + "./dev-tools/check_trailing_spaces.sh", + "./dev-tools/check_shell_scripts.sh", + "./dev-tools/check_no_american_english.sh", + "@composer dump-autoload --dry-run --optimize --strict-psr", + "@normalize", + "@analyse-deps", + "@auto-review" + ], + "static-analysis": [ + "@cs:check", + "@phpstan", + "@php-compatibility", + "@mess-detector" + ], + "test": "@test:all", + "test:all": [ + "@test:unit", + "@test:short-open-tag", + "@test:integration" + ], + "test:coverage": [ + "Composer\\Config::disableProcessTimeout", + "@composer show facile-it/paraunit ^2 && (paraunit coverage --testsuite unit --pass-through=--exclude-group=covers-nothing --pass-through=--do-not-fail-on-empty-test-suite) || (paraunit coverage --testsuite unit --exclude-group covers-nothing)" + ], + "test:integration": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/bin/paraunit run --testsuite integration" + ], + "test:mutation": [ + "Composer\\Config::disableProcessTimeout", + "infection --threads=max --only-covering-test-cases --min-covered-msi=80" + ], + "test:short-open-tag": [ + "Composer\\Config::disableProcessTimeout", + "@php -d short_open_tag=1 ./vendor/bin/phpunit --do-not-cache-result --testsuite short-open-tag" + ], + "test:smoke": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/bin/paraunit run --testsuite smoke" + ], + "test:unit": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/bin/paraunit run --testsuite unit" + ] + }, + "scripts-descriptions": { + "analyse-deps": "Analyse Composer dependencies", + "auto-review": "Execute Auto-review", + "cs:check": "Check coding standards", + "cs:fix": "Fix coding standards", + "cs:fix:parallel": "⚠️DEPRECATED! Use cs:fix with proper parallel config", + "docs": "Regenerate docs", + "infection": "Alias for 'test:mutation'", + "install-tools": "Install DEV tools", + "internal": "Run internal commands", + "mess-detector": "Analyse code with Mess Detector", + "normalize": "Check normalization for composer.json files", + "normalize:fix": "Run normalization for composer.json files", + "php-compatibility": "Check compatibility with all supported PHP versions", + "phpstan": "Run PHPStan analysis", + "phpstan:baseline": "Dump PHPStan baseline file - use only for updating, do not add new errors when possible", + "post-autoload-dump": "Run additional tasks after installing/updating main dependencies", + "qa": "Alias for 'quality-assurance'", + "quality-assurance": "Run QA suite", + "sa": "Alias for 'static-analysis'", + "self-check": "Run set of self-checks ensuring repository's validity", + "static-analysis": "Run static analysis", + "test": "Alias for 'test:all'", + "test:all": "Run Unit and Integration tests (but *NOT* Smoke tests)", + "test:coverage": "Run tests that provide code coverage", + "test:integration": "Run Integration tests", + "test:mutation": "Run mutation tests", + "test:short-open-tag": "Run tests with \"short_open_tag\" enabled", + "test:smoke": "Run Smoke tests", + "test:unit": "Run Unit tests" + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/php-cs-fixer b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/php-cs-fixer new file mode 100755 index 0000000..89db199 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/php-cs-fixer @@ -0,0 +1,112 @@ +#!/usr/bin/env php + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use Composer\XdebugHandler\XdebugHandler; +use PhpCsFixer\Console\Application; + +error_reporting(\E_ALL & ~\E_DEPRECATED & ~\E_USER_DEPRECATED); + +set_error_handler(static function (int $severity, string $message, string $file, int $line): bool { + if (0 !== ($severity & error_reporting())) { + throw new \ErrorException($message, 0, $severity, $file, $line); + } + + return true; +}); + +// check environment requirements +(static function (): void { + if (\PHP_VERSION_ID === (int) '80000') { // TODO use 8_00_00 once only PHP 7.4+ is supported by this entry file + fwrite(\STDERR, "PHP CS Fixer is not able run on PHP 8.0.0 due to bug in PHP tokenizer (https://bugs.php.net/bug.php?id=80462).\n"); + fwrite(\STDERR, "Update PHP version to unblock execution.\n"); + + exit(1); + } + + // PHPStan knows our min PHP version, but we want to check the min version here + // because entrypoint file allows wider PHP range than project itself + // @phpstan-ignore smaller.alwaysFalse + if (\PHP_VERSION_ID < (int) '70400') { + fwrite(\STDERR, "PHP needs to be a minimum version of PHP 7.4.0.\n"); + fwrite(\STDERR, 'Current PHP version: '.\PHP_VERSION.".\n"); + + exit(1); + } + + // @TODO 4.0 cleanup + if (false !== getenv('PHP_CS_FIXER_IGNORE_ENV')) { + fwrite(\STDERR, "Setting PHP_CS_FIXER_IGNORE_ENV environment variable is deprecated and will be removed in 4.0, use unsupportedPhpVersionAllowed config instead.\n"); + } + + foreach (['json', 'tokenizer'] as $extension) { + if (!\extension_loaded($extension)) { + fwrite(\STDERR, \sprintf("PHP extension ext-%s is missing from your system. Install or enable it.\n", $extension)); + + if (filter_var(getenv('PHP_CS_FIXER_IGNORE_ENV'), \FILTER_VALIDATE_BOOLEAN)) { + fwrite(\STDERR, "Ignoring environment requirements because `PHP_CS_FIXER_IGNORE_ENV` is set. Execution may be unstable.\n"); + } else { + exit(1); + } + } + } +})(); + +// load dependencies +(static function (): void { + $require = true; + if (class_exists(\Phar::class)) { + // Maybe this file is used as phar-stub? Let's try! + try { + \Phar::mapPhar('php-cs-fixer.phar'); + + /** @phpstan-ignore requireOnce.fileNotFound */ + require_once 'phar://php-cs-fixer.phar/vendor/autoload.php'; + + $require = false; + } catch (\PharException $e) { + } + } + + if ($require) { + // OK, it's not, let give Composer autoloader a try! + $possibleFiles = [__DIR__.'/../../autoload.php', __DIR__.'/../autoload.php', __DIR__.'/vendor/autoload.php']; + $file = null; + foreach ($possibleFiles as $possibleFile) { + if (file_exists($possibleFile)) { + $file = $possibleFile; + + break; + } + } + + if (null === $file) { + throw new \RuntimeException('Unable to locate autoload.php file.'); + } + + require_once $file; + } +})(); + +// Restart if xdebug is loaded, unless the environment variable PHP_CS_FIXER_ALLOW_XDEBUG is set. +$xdebug = new XdebugHandler('PHP_CS_FIXER'); +$xdebug->check(); +unset($xdebug); + +$application = new Application(); +$application->run(); + +__HALT_COMPILER(); diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/resources/.php-cs-fixer.dist.php.template b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/resources/.php-cs-fixer.dist.php.template new file mode 100644 index 0000000..bdd3711 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/resources/.php-cs-fixer.dist.php.template @@ -0,0 +1,26 @@ +setRiskyAllowed(/*{{ IS_RISKY_ALLOWED }}*/) + ->setRules(/*{{ RULES }}*/) + // 💡 by default, Fixer looks for `*.php` files excluding `./vendor/` - here, you can groom this config + ->setFinder( + (new Finder()) + // 💡 root folder to check + ->in(__DIR__) + // 💡 additional files, eg bin entry file + // ->append([__DIR__.'/bin-entry-file']) + // 💡 folders to exclude, if any + // ->exclude([/* ... */]) + // 💡 path patterns to exclude, if any + // ->notPath([/* ... */]) + // 💡 extra configs + // ->ignoreDotFiles(false) // true by default in v3, false in v4 or future mode + // ->ignoreVCS(true) // true by default + ) +; diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php new file mode 100644 index 0000000..c96ff54 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php @@ -0,0 +1,228 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Doctrine\Annotation\Tokens as DoctrineAnnotationTokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @internal + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ignored_tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ignored_tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractDoctrineAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const CLASS_MODIFIERS = [\T_ABSTRACT, \T_FINAL, FCT::T_READONLY]; + private const MODIFIER_KINDS = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_NS_SEPARATOR, \T_STRING, CT::T_NULLABLE_TYPE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + /** + * @var array + */ + private array $classyElements; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // fetch indices one time, this is safe as we never add or remove a token during fixing + $analyzer = new TokensAnalyzer($tokens); + $this->classyElements = $analyzer->getClassyElements(); + + foreach ($tokens->findGivenKind(\T_DOC_COMMENT) as $index => $docCommentToken) { + if (!$this->nextElementAcceptsDoctrineAnnotations($tokens, $index)) { + continue; + } + + $doctrineAnnotationTokens = DoctrineAnnotationTokens::createFromDocComment( + $docCommentToken, + $this->configuration['ignored_tags'], // @phpstan-ignore-line + ); + + $this->fixAnnotations($doctrineAnnotationTokens); + $tokens[$index] = new Token([\T_DOC_COMMENT, $doctrineAnnotationTokens->getCode()]); + } + } + + /** + * Fixes Doctrine annotations from the given PHPDoc style comment. + */ + abstract protected function fixAnnotations(DoctrineAnnotationTokens $doctrineAnnotationTokens): void; + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of tags that must not be treated as Doctrine Annotations.')) + ->setAllowedTypes(['string[]']) + ->setDefault([ + // PHPDocumentor 1 + 'abstract', + 'access', + 'code', + 'deprec', + 'encode', + 'exception', + 'final', + 'ingroup', + 'inheritdoc', + 'inheritDoc', + 'magic', + 'name', + 'toc', + 'tutorial', + 'private', + 'static', + 'staticvar', + 'staticVar', + 'throw', + + // PHPDocumentor 2 + 'api', + 'author', + 'category', + 'copyright', + 'deprecated', + 'example', + 'filesource', + 'global', + 'ignore', + 'internal', + 'license', + 'link', + 'method', + 'package', + 'param', + 'property', + 'property-read', + 'property-write', + 'return', + 'see', + 'since', + 'source', + 'subpackage', + 'throws', + 'todo', + 'TODO', + 'usedBy', + 'uses', + 'var', + 'version', + + // PHPUnit + 'after', + 'afterClass', + 'backupGlobals', + 'backupStaticAttributes', + 'before', + 'beforeClass', + 'codeCoverageIgnore', + 'codeCoverageIgnoreStart', + 'codeCoverageIgnoreEnd', + 'covers', + 'coversDefaultClass', + 'coversNothing', + 'dataProvider', + 'depends', + 'expectedException', + 'expectedExceptionCode', + 'expectedExceptionMessage', + 'expectedExceptionMessageRegExp', + 'group', + 'large', + 'medium', + 'preserveGlobalState', + 'requires', + 'runTestsInSeparateProcesses', + 'runInSeparateProcess', + 'small', + 'test', + 'testdox', + 'ticket', + 'uses', + + // PHPCheckStyle + 'SuppressWarnings', + + // PHPStorm + 'noinspection', + + // PEAR + 'package_version', + + // PlantUML + 'enduml', + 'startuml', + + // Psalm + 'psalm', + + // PHPStan + 'phpstan', + 'template', + + // other + 'fix', + 'FIXME', + 'fixme', + 'override', + ]) + ->getOption(), + ]); + } + + private function nextElementAcceptsDoctrineAnnotations(Tokens $tokens, int $index): bool + { + do { + $index = $tokens->getNextMeaningfulToken($index); + + if (null === $index) { + return false; + } + } while ($tokens[$index]->isGivenKind(self::CLASS_MODIFIERS)); + + if ($tokens[$index]->isGivenKind(\T_CLASS)) { + return true; + } + + while ($tokens[$index]->isGivenKind(self::MODIFIER_KINDS)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!isset($this->classyElements[$index])) { + return false; + } + + return $tokens[$this->classyElements[$index]['classIndex']]->isGivenKind(\T_CLASS); // interface, enums and traits cannot have doctrine annotations + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php new file mode 100644 index 0000000..0a40386 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractFixer implements FixerInterface +{ + protected WhitespacesFixerConfig $whitespacesConfig; + + /** + * @readonly + */ + private string $name; + + public function __construct() + { + $nameParts = explode('\\', static::class); + $name = substr(end($nameParts), 0, -\strlen('Fixer')); + $this->name = Utils::camelCaseToUnderscore($name); + + if ($this instanceof ConfigurableFixerInterface) { + try { + $this->configure([]); + } catch (RequiredFixerConfigurationException $e) { + // ignore + } + } + + if ($this instanceof WhitespacesAwareFixerInterface) { + $this->whitespacesConfig = $this->getDefaultWhitespacesFixerConfig(); + } + } + + final public function fix(\SplFileInfo $file, Tokens $tokens): void + { + if ($this instanceof ConfigurableFixerInterface && property_exists($this, 'configuration') && null === $this->configuration) { + throw new RequiredFixerConfigurationException($this->getName(), 'Configuration is required.'); + } + + if (0 < $tokens->count() && $this->isCandidate($tokens) && $this->supports($file)) { + $this->applyFix($file, $tokens); + } + } + + public function isRisky(): bool + { + return false; + } + + public function getName(): string + { + return $this->name; + } + + public function getPriority(): int + { + return 0; + } + + public function supports(\SplFileInfo $file): bool + { + return true; + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void + { + if (!$this instanceof WhitespacesAwareFixerInterface) { + throw new \LogicException('Cannot run method for class not implementing "PhpCsFixer\Fixer\WhitespacesAwareFixerInterface".'); + } + + $this->whitespacesConfig = $config; + } + + abstract protected function applyFix(\SplFileInfo $file, Tokens $tokens): void; + + private function getDefaultWhitespacesFixerConfig(): WhitespacesFixerConfig + { + static $defaultWhitespacesFixerConfig = null; + + if (null === $defaultWhitespacesFixerConfig) { + $defaultWhitespacesFixerConfig = new WhitespacesFixerConfig(' ', "\n"); + } + + return $defaultWhitespacesFixerConfig; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php new file mode 100644 index 0000000..ed169c9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractFopenFlagFixer extends AbstractFunctionReferenceFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_STRING, \T_CONSTANT_ENCAPSED_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $index = 0; + $end = $tokens->count() - 1; + while (true) { + $candidate = $this->find('fopen', $tokens, $index, $end); + + if (null === $candidate) { + break; + } + + $index = $candidate[1]; // proceed to '(' of `fopen` + + // fetch arguments + $arguments = $argumentsAnalyzer->getArguments( + $tokens, + $index, + $candidate[2], + ); + + $argumentsCount = \count($arguments); // argument count sanity check + + if ($argumentsCount < 2 || $argumentsCount > 4) { + continue; + } + + // get second argument index + $argumentKeys = array_keys($arguments); + \assert(isset($argumentKeys[1])); + $argumentStartIndex = $argumentKeys[1]; + + \assert(isset($arguments[$argumentStartIndex])); + $this->fixFopenFlagToken( + $tokens, + $argumentStartIndex, + $arguments[$argumentStartIndex], + ); + } + } + + abstract protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void; + + protected function isValidModeString(string $mode): bool + { + $modeLength = \strlen($mode); + if ($modeLength < 1 || $modeLength > 13) { // 13 === length 'r+w+a+x+c+etb' + return false; + } + + $validFlags = [ + 'a' => true, + 'b' => true, + 'c' => true, + 'e' => true, + 'r' => true, + 't' => true, + 'w' => true, + 'x' => true, + ]; + + if (!isset($validFlags[$mode[0]])) { + return false; + } + + unset($validFlags[$mode[0]]); + + for ($i = 1; $i < $modeLength; ++$i) { + if (isset($validFlags[$mode[$i]])) { + unset($validFlags[$mode[$i]]); + + continue; + } + + if ('+' !== $mode[$i] + || ( + 'a' !== $mode[$i - 1] // 'a+','c+','r+','w+','x+' + && 'c' !== $mode[$i - 1] + && 'r' !== $mode[$i - 1] + && 'w' !== $mode[$i - 1] + && 'x' !== $mode[$i - 1] + ) + ) { + return false; + } + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php new file mode 100644 index 0000000..2e53056 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @author Vladimir Reznichenko + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractFunctionReferenceFixer extends AbstractFixer +{ + private ?FunctionsAnalyzer $functionsAnalyzer = null; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * Looks up Tokens sequence for suitable candidates and delivers boundaries information, + * which can be supplied by other methods in this abstract class. + * + * @return ?array{int, int, int} returns $functionName, $openParenthesis, $closeParenthesis packed into array + */ + protected function find(string $functionNameToSearch, Tokens $tokens, int $start = 0, ?int $end = null): ?array + { + if (null === $this->functionsAnalyzer) { + $this->functionsAnalyzer = new FunctionsAnalyzer(); + } + + // make interface consistent with findSequence + $end ??= $tokens->count(); + + // find raw sequence which we can analyse for context + $candidateSequence = [[\T_STRING, $functionNameToSearch], '(']; + $matches = $tokens->findSequence($candidateSequence, $start, $end, false); + + if (null === $matches) { + return null; // not found, simply return without further attempts + } + + // translate results for humans + \assert(isset(array_keys($matches)[1])); + [$functionName, $openParenthesis] = array_keys($matches); + + if (!$this->functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) { + return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end); + } + + return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis)]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php new file mode 100644 index 0000000..8ac22a4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php @@ -0,0 +1,207 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractNoUselessElseFixer extends AbstractFixer +{ + public function getPriority(): int + { + // should be run before NoWhitespaceInBlankLineFixer, NoExtraBlankLinesFixer, BracesFixer and after NoEmptyStatementFixer. + return 39; + } + + protected function isSuperfluousElse(Tokens $tokens, int $index): bool + { + $previousBlockStart = $index; + + do { + // Check if all 'if', 'else if ' and 'elseif' blocks above this 'else' always end, + // if so this 'else' is overcomplete. + [$previousBlockStart, $previousBlockEnd] = $this->getPreviousBlock($tokens, $previousBlockStart); + + // short 'if' detection + $previous = $previousBlockEnd; + if ($tokens[$previous]->equals('}')) { + $previous = $tokens->getPrevMeaningfulToken($previous); + } + + if ( + !$tokens[$previous]->equals(';') // 'if' block doesn't end with semicolon, keep 'else' + || $tokens[$tokens->getPrevMeaningfulToken($previous)]->equals('{') // empty 'if' block, keep 'else' + ) { + return false; + } + + $candidateIndex = $tokens->getPrevTokenOfKind( + $previous, + [ + ';', + [\T_BREAK], + [\T_CLOSE_TAG], + [\T_CONTINUE], + [\T_EXIT], + [\T_GOTO], + [\T_IF], + [\T_RETURN], + [\T_THROW], + ], + ); + + if (null === $candidateIndex || $tokens[$candidateIndex]->equalsAny([';', [\T_CLOSE_TAG], [\T_IF]])) { + return false; + } + + if ($tokens[$candidateIndex]->isGivenKind(\T_THROW)) { + $previousIndex = $tokens->getPrevMeaningfulToken($candidateIndex); + + if (!$tokens[$previousIndex]->equalsAny([';', '{'])) { + return false; + } + } + + if ($this->isInConditional($tokens, $candidateIndex, $previousBlockStart) + || $this->isInConditionWithoutBraces($tokens, $candidateIndex, $previousBlockStart) + ) { + return false; + } + + // implicit continue, i.e. delete candidate + } while (!$tokens[$previousBlockStart]->isGivenKind(\T_IF)); + + return true; + } + + /** + * Return the first and last token index of the previous block. + * + * [0] First is either T_IF, T_ELSE or T_ELSEIF + * [1] Last is either '}' or ';' / T_CLOSE_TAG for short notation blocks + * + * @param int $index T_IF, T_ELSE, T_ELSEIF + * + * @return array{int, int} + */ + private function getPreviousBlock(Tokens $tokens, int $index): array + { + $close = $previous = $tokens->getPrevMeaningfulToken($index); + // short 'if' detection + if ($tokens[$close]->equals('}')) { + $previous = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $close); + } + + $open = $tokens->getPrevTokenOfKind($previous, [[\T_IF], [\T_ELSE], [\T_ELSEIF]]); + if ($tokens[$open]->isGivenKind(\T_IF)) { + $elseCandidate = $tokens->getPrevMeaningfulToken($open); + if ($tokens[$elseCandidate]->isGivenKind(\T_ELSE)) { + $open = $elseCandidate; + } + } + + return [$open, $close]; + } + + /** + * @param int $index Index of the token to check + * @param int $lowerLimitIndex Lower limit index. Since the token to check will always be in a conditional we must stop checking at this index + */ + private function isInConditional(Tokens $tokens, int $index, int $lowerLimitIndex): bool + { + $candidateIndex = $tokens->getPrevTokenOfKind($index, [')', ';', ':']); + if ($tokens[$candidateIndex]->equals(':')) { + return true; + } + + if (!$tokens[$candidateIndex]->equals(')')) { + return false; // token is ';' or close tag + } + + // token is always ')' here. + // If it is part of the condition the token is always in, return false. + // If it is not it is a nested condition so return true + $open = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $candidateIndex); + + return $tokens->getPrevMeaningfulToken($open) > $lowerLimitIndex; + } + + /** + * For internal use only, as it is not perfect. + * + * Returns if the token at given index is part of an if/elseif/else statement + * without {}. Assumes not passing the last `;`/close tag of the statement, not + * out of range index, etc. + * + * @param int $index Index of the token to check + */ + private function isInConditionWithoutBraces(Tokens $tokens, int $index, int $lowerLimitIndex): bool + { + do { + if ($tokens[$index]->isComment() || $tokens[$index]->isWhitespace()) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + $token = $tokens[$index]; + if ($token->isGivenKind([\T_IF, \T_ELSEIF, \T_ELSE])) { + return true; + } + + if ($token->equals(';')) { + return false; + } + + if ($token->equals('{')) { + $index = $tokens->getPrevMeaningfulToken($index); + + // OK if belongs to: for, do, while, foreach + // Not OK if belongs to: if, else, elseif + if ($tokens[$index]->isGivenKind(\T_DO)) { + --$index; + + continue; + } + + if (!$tokens[$index]->equals(')')) { + return false; // like `else {` + } + + $index = $tokens->findBlockStart( + Tokens::BLOCK_TYPE_PARENTHESIS, + $index, + ); + + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isGivenKind([\T_IF, \T_ELSEIF])) { + return false; + } + } elseif ($token->equals(')')) { + $type = Tokens::detectBlockType($token); + $index = $tokens->findBlockStart( + $type['type'], + $index, + ); + + $index = $tokens->getPrevMeaningfulToken($index); + } else { + --$index; + } + } while ($index > $lowerLimitIndex); + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php new file mode 100644 index 0000000..ee620ed --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php @@ -0,0 +1,348 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @phpstan-type _CommonTypeInfo array{commonType: string, isNullable: bool} + * @phpstan-type _AutogeneratedInputConfiguration array{ + * scalar_types?: bool, + * types_map?: array, + * union_types?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * scalar_types: bool, + * types_map: array, + * union_types: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractPhpdocToTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER + .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; + + /** + * @var array + */ + private array $versionSpecificTypes = [ + 'void' => 7_01_00, + 'iterable' => 7_01_00, + 'object' => 7_02_00, + 'mixed' => 8_00_00, + 'never' => 8_01_00, + ]; + + /** + * @var array + */ + private array $scalarTypes = [ + 'bool' => true, + 'float' => true, + 'int' => true, + 'string' => true, + ]; + + /** + * @var array + */ + private static array $syntaxValidationCache = []; + + public function isRisky(): bool + { + return true; + } + + abstract protected function isSkippedType(string $type): bool; + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('scalar_types', 'Fix also scalar types; may have unexpected behaviour due to PHP bad type coercion system.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('union_types', 'Fix also union types; turned on by default on PHP >= 8.0.0.')) + ->setAllowedTypes(['bool']) + ->setDefault(\PHP_VERSION_ID >= 8_00_00) + ->getOption(), + (new FixerOptionBuilder('types_map', 'Map of custom types, e.g. template types from PHPStan.')) + ->setAllowedTypes(['array']) + ->setDefault([]) + ->getOption(), + ]); + } + + /** + * @param int $index The index of the function token + */ + protected function findFunctionDocComment(Tokens $tokens, int $index): ?int + { + do { + $index = $tokens->getPrevNonWhitespace($index); + } while ($tokens[$index]->isGivenKind([ + \T_COMMENT, + \T_ABSTRACT, + \T_FINAL, + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_STATIC, + ])); + + if ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + return $index; + } + + return null; + } + + /** + * @return list + */ + protected function getAnnotationsFromDocComment(string $name, Tokens $tokens, int $docCommentIndex): array + { + $namespacesAnalyzer = new NamespacesAnalyzer(); + $namespace = $namespacesAnalyzer->getNamespaceAt($tokens, $docCommentIndex); + + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $namespaceUses = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + + $doc = new DocBlock( + $tokens[$docCommentIndex]->getContent(), + $namespace, + $namespaceUses, + ); + + return $doc->getAnnotationsOfType($name); + } + + /** + * @return list + */ + protected function createTypeDeclarationTokens(string $type, bool $isNullable): array + { + $newTokens = []; + + if (true === $isNullable && 'mixed' !== $type) { + $newTokens[] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + + $newTokens = array_merge( + $newTokens, + $this->createTokensFromRawType($type)->toArray(), + ); + + // 'scalar's, 'void', 'iterable' and 'object' must be unqualified + foreach ($newTokens as $i => $token) { + if ($token->isGivenKind(\T_STRING)) { + $typeUnqualified = $token->getContent(); + + if ( + (isset($this->scalarTypes[$typeUnqualified]) || isset($this->versionSpecificTypes[$typeUnqualified])) + && isset($newTokens[$i - 1]) + && '\\' === $newTokens[$i - 1]->getContent() + ) { + unset($newTokens[$i - 1]); + } + } + } + + return array_values($newTokens); + } + + /** + * Each fixer inheriting from this class must define a way of creating token collection representing type + * gathered from phpDoc, e.g. `Foo|Bar` should be transformed into 3 tokens (`Foo`, `|` and `Bar`). + * This can't be standardised, because some types may be allowed in one place, and invalid in others. + * + * @param string $type Type determined (and simplified) from phpDoc + */ + abstract protected function createTokensFromRawType(string $type): Tokens; + + /** + * @return ?_CommonTypeInfo + */ + protected function getCommonTypeInfo(TypeExpression $typesExpression, bool $isReturnType): ?array + { + $commonType = $typesExpression->getCommonType(); + $isNullable = $typesExpression->allowsNull(); + + if (null === $commonType) { + return null; + } + + if ($isNullable && 'void' === $commonType) { + return null; + } + + if ('static' === $commonType && (!$isReturnType || \PHP_VERSION_ID < 8_00_00)) { + $commonType = 'self'; + } + + if ($this->isSkippedType($commonType)) { + return null; + } + + if (\array_key_exists($commonType, $this->configuration['types_map'])) { + $commonType = $this->configuration['types_map'][$commonType]; + } + + if (isset($this->versionSpecificTypes[$commonType]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$commonType]) { + return null; + } + + if (isset($this->scalarTypes[$commonType])) { + if (false === $this->configuration['scalar_types']) { + return null; + } + } elseif (!Preg::match('/^'.self::REGEX_CLASS.'$/', $commonType)) { + return null; + } + + return ['commonType' => $commonType, 'isNullable' => $isNullable]; + } + + protected function getUnionTypes(TypeExpression $typesExpression, bool $isReturnType): ?string + { + if (\PHP_VERSION_ID < 8_00_00) { + return null; + } + + if (!$typesExpression->isUnionType()) { + return null; + } + + if (false === $this->configuration['union_types']) { + return null; + } + + $types = $typesExpression->getTypes(); + $isNullable = $typesExpression->allowsNull(); + $unionTypes = []; + $containsOtherThanIterableType = false; + $containsOtherThanEmptyType = false; + + foreach ($types as $type) { + if ('null' === $type) { + continue; + } + + if ($this->isSkippedType($type)) { + return null; + } + + if (isset($this->versionSpecificTypes[$type]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$type]) { + return null; + } + + $typeExpression = new TypeExpression($type, null, []); + $commonTypeInfo = $this->getCommonTypeInfo($typeExpression, $isReturnType); + + if (null === $commonTypeInfo) { + return null; + } + + $commonType = $commonTypeInfo['commonType']; + + if (!$containsOtherThanIterableType && !\in_array($commonType, ['array', \Traversable::class, 'iterable'], true)) { + $containsOtherThanIterableType = true; + } + if ($isReturnType && !$containsOtherThanEmptyType && !\in_array($commonType, ['null', 'void', 'never'], true)) { + $containsOtherThanEmptyType = true; + } + + if (!$isNullable && $commonTypeInfo['isNullable']) { + $isNullable = true; + } + + $unionTypes[] = $commonType; + } + + if (!$containsOtherThanIterableType) { + return null; + } + if ($isReturnType && !$containsOtherThanEmptyType) { + return null; + } + + if ($isNullable) { + $unionTypes[] = 'null'; + } + + return implode($typesExpression->getTypesGlue(), array_unique($unionTypes)); + } + + final protected function isValidSyntax(string $code): bool + { + if (!isset(self::$syntaxValidationCache[$code])) { + try { + Tokens::fromCode($code); + self::$syntaxValidationCache[$code] = true; + } catch (\ParseError $e) { + self::$syntaxValidationCache[$code] = false; + } + } + + return self::$syntaxValidationCache[$code]; + } + + /** + * @return list + */ + final protected static function getTypesToExclude(string $content): array + { + $typesToExclude = []; + + $docBlock = new DocBlock($content); + + foreach ($docBlock->getAnnotationsOfType(['phpstan-type', 'psalm-type']) as $annotation) { + $typesToExclude[] = $annotation->getTypeExpression()->toString(); + } + + foreach ($docBlock->getAnnotationsOfType(['phpstan-import-type', 'psalm-import-type']) as $annotation) { + $content = trim($annotation->getContent()); + if (Preg::match('/\bas\s+('.TypeExpression::REGEX_IDENTIFIER.')$/', $content, $matches)) { + $typesToExclude[] = $matches[1]; + + continue; + } + $typesToExclude[] = $annotation->getTypeExpression()->toString(); + } + + return $typesToExclude; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php new file mode 100644 index 0000000..c8cdebe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * This abstract fixer provides a base for fixers to fix types in PHPDoc. + * + * @author Graham Campbell + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractPhpdocTypesFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $this->fixType($annotation); + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * Actually normalize the given type. + */ + abstract protected function normalize(string $type): string; + + /** + * Fix the type at the given line. + * + * We must be super careful not to modify parts of words. + * + * This will be nicely handled behind the scenes for us by the annotation class. + */ + private function fixType(Annotation $annotation): void + { + $typeExpression = $annotation->getTypeExpression(); + + if (null === $typeExpression) { + return; + } + + $newTypeExpression = $typeExpression->mapTypes(function (TypeExpression $type) { + if (!$type->isCompositeType()) { + $value = $this->normalize($type->toString()); + + return new TypeExpression($value, null, []); + } + + return $type; + }); + + $annotation->setTypes([$newTypeExpression->toString()]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php new file mode 100644 index 0000000..3bd1d19 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractProxyFixer extends AbstractFixer +{ + /** + * @var non-empty-array + */ + protected array $proxyFixers; + + public function __construct() + { + $proxyFixers = []; + foreach (Utils::sortFixers($this->createProxyFixers()) as $proxyFixer) { + $proxyFixers[$proxyFixer->getName()] = $proxyFixer; + } + $this->proxyFixers = $proxyFixers; + + parent::__construct(); + } + + public function isCandidate(Tokens $tokens): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isCandidate($tokens)) { + return true; + } + } + + return false; + } + + public function isRisky(): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isRisky()) { + return true; + } + } + + return false; + } + + public function getPriority(): int + { + if (\count($this->proxyFixers) > 1) { + throw new \LogicException('You need to override this method to provide the priority of combined fixers.'); + } + + return reset($this->proxyFixers)->getPriority(); + } + + public function supports(\SplFileInfo $file): bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->supports($file)) { + return true; + } + } + + return false; + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void + { + parent::setWhitespacesConfig($config); + + foreach ($this->proxyFixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->proxyFixers as $fixer) { + $fixer->fix($file, $tokens); + } + } + + /** + * @return non-empty-list + */ + abstract protected function createProxyFixers(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php new file mode 100644 index 0000000..b713784 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use PhpCsFixer\Config\NullRuleCustomisationPolicy; +use PhpCsFixer\Utils; + +/** + * @author Andreas Möller + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Cache implements CacheInterface +{ + private SignatureInterface $signature; + + /** + * @var array + */ + private array $hashes = []; + + public function __construct(SignatureInterface $signature) + { + $this->signature = $signature; + } + + public function getSignature(): SignatureInterface + { + return $this->signature; + } + + public function has(string $file): bool + { + return \array_key_exists($file, $this->hashes); + } + + public function get(string $file): ?string + { + return $this->hashes[$file] ?? null; + } + + public function set(string $file, string $hash): void + { + $this->hashes[$file] = $hash; + } + + public function clear(string $file): void + { + unset($this->hashes[$file]); + } + + public function toJson(): string + { + try { + return json_encode( + [ + 'php' => $this->getSignature()->getPhpVersion(), + 'version' => $this->getSignature()->getFixerVersion(), + 'indent' => $this->getSignature()->getIndent(), + 'lineEnding' => $this->getSignature()->getLineEnding(), + 'rules' => $this->getSignature()->getRules(), + 'ruleCustomisationPolicyVersion' => $this->getSignature()->getRuleCustomisationPolicyVersion(), + 'hashes' => $this->hashes, + ], + \JSON_THROW_ON_ERROR, + ); + } catch (\JsonException $e) { + throw new \UnexpectedValueException(\sprintf( + 'Cannot encode cache signature to JSON, error: "%s". If you have non-UTF8 chars in your signature, like in license for `header_comment`, consider enabling `ext-mbstring` or install `symfony/polyfill-mbstring`.', + $e->getMessage(), + )); + } + } + + /** + * @throws \InvalidArgumentException + */ + public static function fromJson(string $json): self + { + try { + $data = json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \InvalidArgumentException(\sprintf( + 'Value needs to be a valid JSON string, got "%s", error: "%s".', + $json, + $e->getMessage(), + )); + } + + $requiredKeys = [ + 'php', + 'version', + 'indent', + 'lineEnding', + 'rules', + // 'ruleCustomisationPolicyVersion', // @TODO v4: require me + 'hashes', + ]; + + $missingKeys = array_diff_key(array_flip($requiredKeys), $data); + + if (\count($missingKeys) > 0) { + throw new \InvalidArgumentException(\sprintf( + 'JSON data is missing keys %s', + Utils::naturalLanguageJoin(array_keys($missingKeys)), + )); + } + + $signature = new Signature( + $data['php'], + $data['version'], + $data['indent'], + $data['lineEnding'], + $data['rules'], + $data['ruleCustomisationPolicyVersion'] ?? NullRuleCustomisationPolicy::VERSION_FOR_CACHE, + ); + + $cache = new self($signature); + + // before v3.11.1 the hashes were crc32 encoded and saved as integers + // @TODO v4: remove the to string cast/array_map + $cache->hashes = array_map(static fn ($v): string => \is_int($v) ? (string) $v : $v, $data['hashes']); + + return $cache; + } + + /** + * @internal + */ + public function backfillHashes(self $oldCache): bool + { + if (!$this->getSignature()->equals($oldCache->getSignature())) { + return false; + } + + $this->hashes = array_merge($oldCache->hashes, $this->hashes); + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php new file mode 100644 index 0000000..2a6cca9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface CacheInterface +{ + public function getSignature(): SignatureInterface; + + public function has(string $file): bool; + + public function get(string $file): ?string; + + public function set(string $file, string $hash): void; + + public function clear(string $file): void; + + public function toJson(): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php new file mode 100644 index 0000000..3115344 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent): bool; + + public function setFile(string $file, string $fileContent): void; + + public function setFileHash(string $file, string $hash): void; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php new file mode 100644 index 0000000..e7bc196 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Directory implements DirectoryInterface +{ + private string $directoryName; + + public function __construct(string $directoryName) + { + $this->directoryName = $directoryName; + } + + public function getRelativePathTo(string $file): string + { + $file = $this->normalizePath($file); + + if ( + '' === $this->directoryName + || !str_starts_with(strtolower($file), strtolower($this->directoryName.\DIRECTORY_SEPARATOR)) + ) { + return $file; + } + + return substr($file, \strlen($this->directoryName) + 1); + } + + private function normalizePath(string $path): string + { + return str_replace(['\\', '/'], \DIRECTORY_SEPARATOR, $path); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php new file mode 100644 index 0000000..9b5bb26 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface DirectoryInterface +{ + public function getRelativePathTo(string $file): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php new file mode 100644 index 0000000..5c539f0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use PhpCsFixer\Hasher; + +/** + * Class supports caching information about state of fixing files. + * + * Cache is supported only for phar version and version installed via composer. + * + * File will be processed by PHP CS Fixer only if any of the following conditions is fulfilled: + * - cache is corrupt + * - fixer version changed + * - rules changed + * - file is new + * - file changed + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileCacheManager implements CacheManagerInterface +{ + public const WRITE_FREQUENCY = 10; + + private FileHandlerInterface $handler; + + private SignatureInterface $signature; + + private bool $isDryRun; + + private DirectoryInterface $cacheDirectory; + + private int $writeCounter = 0; + + private bool $signatureWasUpdated = false; + + private CacheInterface $cache; + + public function __construct( + FileHandlerInterface $handler, + SignatureInterface $signature, + bool $isDryRun = false, + ?DirectoryInterface $cacheDirectory = null + ) { + $this->handler = $handler; + $this->signature = $signature; + $this->isDryRun = $isDryRun; + $this->cacheDirectory = $cacheDirectory ?? new Directory(''); + + $this->readCache(); + } + + public function __destruct() + { + if (true === $this->signatureWasUpdated || 0 !== $this->writeCounter) { + $this->writeCache(); + } + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __serialize(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @param array $data + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __unserialize(array $data): void + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function needFixing(string $file, string $fileContent): bool + { + $file = $this->cacheDirectory->getRelativePathTo($file); + + return !$this->cache->has($file) || $this->cache->get($file) !== $this->calcHash($fileContent); + } + + public function setFile(string $file, string $fileContent): void + { + $this->setFileHash($file, $this->calcHash($fileContent)); + } + + public function setFileHash(string $file, string $hash): void + { + $file = $this->cacheDirectory->getRelativePathTo($file); + + if ($this->isDryRun && $this->cache->has($file) && $this->cache->get($file) !== $hash) { + $this->cache->clear($file); + } else { + $this->cache->set($file, $hash); + } + + if (self::WRITE_FREQUENCY === ++$this->writeCounter) { + $this->writeCounter = 0; + $this->writeCache(); + } + } + + private function readCache(): void + { + $cache = $this->handler->read(); + + if (null === $cache || !$this->signature->equals($cache->getSignature())) { + $cache = new Cache($this->signature); + $this->signatureWasUpdated = true; + } + + $this->cache = $cache; + } + + private function writeCache(): void + { + $this->handler->write($this->cache); + } + + private function calcHash(string $content): string + { + return Hasher::calculate($content); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php new file mode 100644 index 0000000..252ed8c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php @@ -0,0 +1,186 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use Symfony\Component\Filesystem\Exception\IOException; + +/** + * @author Andreas Möller + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileHandler implements FileHandlerInterface +{ + private \SplFileInfo $fileInfo; + + private int $fileMTime = 0; + + public function __construct(string $file) + { + $this->fileInfo = new \SplFileInfo($file); + } + + public function getFile(): string + { + return $this->fileInfo->getPathname(); + } + + public function read(): ?CacheInterface + { + if (!$this->fileInfo->isFile() || !$this->fileInfo->isReadable()) { + return null; + } + + $fileObject = $this->fileInfo->openFile('r'); + + $cache = $this->readFromHandle($fileObject); + $this->fileMTime = $this->getFileCurrentMTime(); + + unset($fileObject); // explicitly close file handler + + return $cache; + } + + public function write(CacheInterface $cache): void + { + $this->ensureFileIsWriteable(); + + $fileObject = $this->fileInfo->openFile('r+'); + + if (method_exists($cache, 'backfillHashes') && $this->fileMTime < $this->getFileCurrentMTime()) { + $resultOfFlock = $fileObject->flock(\LOCK_EX); + if (false === $resultOfFlock) { + // Lock failed, OK - we continue without the lock. + // noop + } + + $oldCache = $this->readFromHandle($fileObject); + + $fileObject->rewind(); + + if (null !== $oldCache) { + $cache->backfillHashes($oldCache); + } + } + + $resultOfTruncate = $fileObject->ftruncate(0); + if (false === $resultOfTruncate) { + // Truncate failed. OK - we do not save the cache. + return; + } + + $resultOfWrite = $fileObject->fwrite($cache->toJson()); + if (false === $resultOfWrite) { + // Write failed. OK - we did not save the cache. + return; + } + + $resultOfFlush = $fileObject->fflush(); + if (false === $resultOfFlush) { + // Flush failed. OK - part of cache can be missing, in case this was last chunk in this pid. + // noop + } + + $this->fileMTime = time(); // we could take the fresh `mtime` of file that we just modified with `$this->getFileCurrentMTime()`, but `time()` should be good enough here and reduce IO operation + } + + private function getFileCurrentMTime(): int + { + clearstatcache(true, $this->fileInfo->getPathname()); + + $mtime = $this->fileInfo->getMTime(); + + if (false === $mtime) { + // cannot check mtime? OK - let's pretend file is old. + $mtime = 0; + } + + return $mtime; + } + + private function readFromHandle(\SplFileObject $fileObject): ?CacheInterface + { + try { + $size = $fileObject->getSize(); + if (false === $size || 0 === $size) { + return null; + } + + $content = $fileObject->fread($size); + + if (false === $content) { + return null; + } + + return Cache::fromJson($content); + } catch (\InvalidArgumentException $exception) { + return null; + } + } + + private function ensureFileIsWriteable(): void + { + if ($this->fileInfo->isFile() && $this->fileInfo->isWritable()) { + // all good + return; + } + + if ($this->fileInfo->isDir()) { + throw new IOException( + \sprintf('Cannot write cache file "%s" as the location exists as directory.', $this->fileInfo->getRealPath()), + 0, + null, + $this->fileInfo->getPathname(), + ); + } + + if ($this->fileInfo->isFile() && !$this->fileInfo->isWritable()) { + throw new IOException( + \sprintf('Cannot write to file "%s" as it is not writable.', $this->fileInfo->getRealPath()), + 0, + null, + $this->fileInfo->getPathname(), + ); + } + + $this->createFile($this->fileInfo->getPathname()); + } + + private function createFile(string $file): void + { + $dir = \dirname($file); + + // Ensure path is created, but ignore if already exists. FYI: ignore EA suggestion in IDE, + // `mkdir()` returns `false` for existing paths, so we can't mix it with `is_dir()` in one condition. + if (!@is_dir($dir)) { + @mkdir($dir, 0777, true); + } + + if (!@is_dir($dir)) { + throw new IOException( + \sprintf('Directory of cache file "%s" does not exists and couldn\'t be created.', $file), + 0, + null, + $file, + ); + } + + @touch($file); + @chmod($file, 0666); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php new file mode 100644 index 0000000..7f8b430 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FileHandlerInterface +{ + public function getFile(): string; + + public function read(): ?CacheInterface; + + public function write(CacheInterface $cache): void; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php new file mode 100644 index 0000000..808c0f0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullCacheManager implements CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent): bool + { + return true; + } + + public function setFile(string $file, string $fileContent): void {} + + public function setFileHash(string $file, string $hash): void {} +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php new file mode 100644 index 0000000..a33efa1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +use PhpCsFixer\Future; + +/** + * @author Andreas Möller + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Signature implements SignatureInterface +{ + private string $phpVersion; + + private string $fixerVersion; + + private string $indent; + + private string $lineEnding; + + /** + * @var array|bool> + */ + private array $rules; + + private string $ruleCustomisationPolicyVersion; + + /** + * @param array|bool> $rules + */ + public function __construct(string $phpVersion, string $fixerVersion, string $indent, string $lineEnding, array $rules, string $ruleCustomisationPolicyVersion) + { + $this->phpVersion = $phpVersion; + $this->fixerVersion = $fixerVersion; + $this->indent = $indent; + $this->lineEnding = $lineEnding; + $this->rules = self::makeJsonEncodable($rules); + $this->ruleCustomisationPolicyVersion = $ruleCustomisationPolicyVersion; + } + + public function getPhpVersion(): string + { + return $this->phpVersion; + } + + public function getFixerVersion(): string + { + return $this->fixerVersion; + } + + public function getIndent(): string + { + return $this->indent; + } + + public function getLineEnding(): string + { + return $this->lineEnding; + } + + public function getRules(): array + { + return $this->rules; + } + + public function getRuleCustomisationPolicyVersion(): string + { + return $this->ruleCustomisationPolicyVersion; + } + + public function equals(SignatureInterface $signature): bool + { + return $this->phpVersion === $signature->getPhpVersion() + && $this->fixerVersion === $signature->getFixerVersion() + && $this->indent === $signature->getIndent() + && $this->lineEnding === $signature->getLineEnding() + && $this->rules === $signature->getRules() + && $this->ruleCustomisationPolicyVersion === $signature->getRuleCustomisationPolicyVersion(); + } + + /** + * @param array|bool> $data + * + * @return array|bool> + */ + private static function makeJsonEncodable(array $data): array + { + array_walk_recursive($data, static function (&$item, $key): void { + if (\is_string($item) && false === mb_detect_encoding($item, 'utf-8', true)) { + $item = base64_encode($item); + } elseif (\is_object($item)) { + if ($item instanceof \JsonSerializable) { + $item = \get_class($item).'#'.json_encode($item, \JSON_THROW_ON_ERROR); + } else { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Can not serialize cache signature, unhandled object under "%s" key: "%s" - implement "%s".', + $key, + \get_class($item), + \JsonSerializable::class, + ))); + } + } + }); + + return $data; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php new file mode 100644 index 0000000..19659c6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface SignatureInterface +{ + public function getPhpVersion(): string; + + public function getFixerVersion(): string; + + public function getIndent(): string; + + public function getLineEnding(): string; + + /** + * @return array|bool> + */ + public function getRules(): array; + + public function getRuleCustomisationPolicyVersion(): string; + + public function equals(self $signature): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ComposerJsonReader.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ComposerJsonReader.php new file mode 100644 index 0000000..ed57020 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ComposerJsonReader.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use Composer\Semver\Semver; +use Symfony\Component\Filesystem\Exception\IOException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ComposerJsonReader +{ + private const COMPOSER_FILENAME = 'composer.json'; + + private bool $isProcessed = false; + + private ?string $php = null; + + private ?string $phpUnit = null; + + private static ?self $singleton = null; + + public static function createSingleton(): self + { + if (null === self::$singleton) { + self::$singleton = new self(); + } + + return self::$singleton; + } + + public function getPhp(): ?string + { + $this->processFile(); + + return $this->php; + } + + public function getPhpUnit(): ?string + { + $this->processFile(); + + return $this->phpUnit; + } + + private function processFile(): void + { + if (true === $this->isProcessed) { + return; + } + + if (!file_exists(self::COMPOSER_FILENAME)) { + throw new IOException(\sprintf('Failed to read file "%s".', self::COMPOSER_FILENAME)); + } + + $readResult = file_get_contents(self::COMPOSER_FILENAME); + if (false === $readResult) { + throw new IOException(\sprintf('Failed to read file "%s".', self::COMPOSER_FILENAME)); + } + + $this->processJson($readResult); + } + + private function processJson(string $json): void + { + if (true === $this->isProcessed) { + return; + } + + $composerJson = json_decode($json, true, 512, \JSON_THROW_ON_ERROR); + + $this->php = self::getMinSemVer(self::detectPhp($composerJson)); + $this->phpUnit = self::getMinSemVer(self::detectPackage($composerJson, 'phpunit/phpunit')); + + $this->isProcessed = true; + } + + private static function getMinSemVer(?string $version): ?string + { + if ('' === $version || null === $version) { + return null; + } + + /** @var non-empty-list $arr */ + $arr = Preg::split('/\s*\|\|?\s*/', trim($version)); + + $arr = array_map(static function ($v) { + $v = ltrim($v, 'v^~>= '); + + $v = substr($v, 0, strcspn($v, ' ,-')); + + if (str_ends_with($v, '.*')) { + $v = substr($v, 0, -\strlen('.*')); + } + + return $v; + }, $arr); + + $textVersion = array_find($arr, static fn ($v) => true === Preg::match('/^\D/', $v)); + + if (null !== $textVersion) { + return null; + } + + /** @var non-empty-list $sortedArr */ + $sortedArr = Semver::sort($arr); + + $min = $sortedArr[0]; + $parts = explode('.', $min); + + return \sprintf('%s.%s', (int) $parts[0], (int) ($parts[1] ?? 0)); + } + + /** + * @param array $composerJson + */ + private static function detectPhp(array $composerJson): ?string + { + $version = []; + + if (isset($composerJson['config']['platform']['php'])) { + $version[] = $composerJson['config']['platform']['php']; + } + + if (isset($composerJson['require-dev']['php'])) { + $version[] = $composerJson['require-dev']['php']; + } + + if (isset($composerJson['require']['php'])) { + $version[] = $composerJson['require']['php']; + } + + if (\count($version) > 0) { + return implode(' || ', $version); + } + + return null; + } + + /** + * @param array $composerJson + * @param non-empty-string $package + */ + private static function detectPackage(array $composerJson, string $package): ?string + { + $version = []; + + if (isset($composerJson['require-dev'][$package])) { + $version[] = $composerJson['require-dev'][$package]; + } + + if (isset($composerJson['require'][$package])) { + $version[] = $composerJson['require'][$package]; + } + + if (\count($version) > 0) { + return implode(' || ', $version); + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config.php new file mode 100644 index 0000000..979aef7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config.php @@ -0,0 +1,321 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Config\RuleCustomisationPolicyAwareConfigInterface; +use PhpCsFixer\Config\RuleCustomisationPolicyInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\Runner\Parallel\ParallelConfig; +use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; + +/** + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @api-extendable + */ +class Config implements ConfigInterface, ParallelAwareConfigInterface, UnsupportedPhpVersionAllowedConfigInterface, CustomRulesetsAwareConfigInterface, RuleCustomisationPolicyAwareConfigInterface +{ + /** + * @var non-empty-string + */ + private string $cacheFile = '.php-cs-fixer.cache'; + + /** + * @var list + */ + private array $customFixers = []; + + /** + * @var array + */ + private array $customRuleSets = []; + + /** + * @var null|iterable<\SplFileInfo> + */ + private ?iterable $finder = null; + + private string $format; + + private bool $hideProgress = false; + + /** + * @var non-empty-string + */ + private string $indent = ' '; + + private bool $isRiskyAllowed = false; + + /** + * @var non-empty-string + */ + private string $lineEnding = "\n"; + + private string $name; + + private ParallelConfig $parallelConfig; + + private ?string $phpExecutable = null; + + /** + * @TODO: 4.0 - update to @PER + * + * @var array|bool> + */ + private array $rules; + + private bool $usingCache = true; + + private bool $isUnsupportedPhpVersionAllowed = false; + + private ?RuleCustomisationPolicyInterface $ruleCustomisationPolicy = null; + + public function __construct(string $name = 'default') + { + $this->name = $name.(Future::isFutureModeEnabled() ? ' (future mode)' : ''); + $this->rules = Future::getV4OrV3(['@PER-CS' => true], ['@PSR12' => true]); // @TODO 4.0 | 3.x switch to '@auto' for v4 + $this->format = Future::getV4OrV3('@auto', 'txt'); + $this->parallelConfig = ParallelConfigFactory::detect(); + + // @TODO 4.0 cleanup + if (false !== getenv('PHP_CS_FIXER_IGNORE_ENV')) { + $this->isUnsupportedPhpVersionAllowed = filter_var(getenv('PHP_CS_FIXER_IGNORE_ENV'), \FILTER_VALIDATE_BOOL); + } + } + + /** + * @return non-empty-string + */ + public function getCacheFile(): string + { + return $this->cacheFile; + } + + public function getCustomFixers(): array + { + return $this->customFixers; + } + + public function getCustomRuleSets(): array + { + return array_values($this->customRuleSets); + } + + /** + * @return iterable<\SplFileInfo> + */ + public function getFinder(): iterable + { + $this->finder ??= new Finder(); + + return $this->finder; + } + + public function getFormat(): string + { + return $this->format; + } + + public function getHideProgress(): bool + { + return $this->hideProgress; + } + + public function getIndent(): string + { + return $this->indent; + } + + public function getLineEnding(): string + { + return $this->lineEnding; + } + + public function getName(): string + { + return $this->name; + } + + public function getParallelConfig(): ParallelConfig + { + return $this->parallelConfig; + } + + public function getPhpExecutable(): ?string + { + return $this->phpExecutable; + } + + public function getRiskyAllowed(): bool + { + return $this->isRiskyAllowed; + } + + public function getRules(): array + { + return $this->rules; + } + + public function getUsingCache(): bool + { + return $this->usingCache; + } + + public function getUnsupportedPhpVersionAllowed(): bool + { + return $this->isUnsupportedPhpVersionAllowed; + } + + public function getRuleCustomisationPolicy(): ?RuleCustomisationPolicyInterface + { + return $this->ruleCustomisationPolicy; + } + + public function registerCustomFixers(iterable $fixers): ConfigInterface + { + foreach ($fixers as $fixer) { + $this->addCustomFixer($fixer); + } + + return $this; + } + + /** + * @param list $ruleSets + */ + public function registerCustomRuleSets(array $ruleSets): ConfigInterface + { + foreach ($ruleSets as $ruleset) { + $this->customRuleSets[$ruleset->getName()] = $ruleset; + } + + return $this; + } + + /** + * @param non-empty-string $cacheFile + */ + public function setCacheFile(string $cacheFile): ConfigInterface + { + $this->cacheFile = $cacheFile; + + return $this; + } + + public function setFinder(iterable $finder): ConfigInterface + { + $this->finder = $finder; + + return $this; + } + + public function setFormat(string $format): ConfigInterface + { + $this->format = $format; + + return $this; + } + + public function setHideProgress(bool $hideProgress): ConfigInterface + { + $this->hideProgress = $hideProgress; + + return $this; + } + + /** + * @param non-empty-string $indent + */ + public function setIndent(string $indent): ConfigInterface + { + $this->indent = $indent; + + return $this; + } + + /** + * @param non-empty-string $lineEnding + */ + public function setLineEnding(string $lineEnding): ConfigInterface + { + $this->lineEnding = $lineEnding; + + return $this; + } + + public function setParallelConfig(ParallelConfig $config): ConfigInterface + { + $this->parallelConfig = $config; + + return $this; + } + + public function setPhpExecutable(?string $phpExecutable): ConfigInterface + { + $this->phpExecutable = $phpExecutable; + + return $this; + } + + public function setRiskyAllowed(bool $isRiskyAllowed): ConfigInterface + { + $this->isRiskyAllowed = $isRiskyAllowed; + + return $this; + } + + public function setRules(array $rules): ConfigInterface + { + $this->rules = $rules; + + return $this; + } + + public function setUsingCache(bool $usingCache): ConfigInterface + { + $this->usingCache = $usingCache; + + return $this; + } + + public function setUnsupportedPhpVersionAllowed(bool $isUnsupportedPhpVersionAllowed): ConfigInterface + { + $this->isUnsupportedPhpVersionAllowed = $isUnsupportedPhpVersionAllowed; + + return $this; + } + + public function setRuleCustomisationPolicy(?RuleCustomisationPolicyInterface $ruleCustomisationPolicy): ConfigInterface + { + // explicitly prevent policy with no proper version defined + if (null !== $ruleCustomisationPolicy && '' === $ruleCustomisationPolicy->getPolicyVersionForCache()) { + throw new \InvalidArgumentException('The Rule Customisation Policy version cannot be an empty string.'); + } + + $this->ruleCustomisationPolicy = $ruleCustomisationPolicy; + + return $this; + } + + private function addCustomFixer(FixerInterface $fixer): void + { + $this->customFixers[] = $fixer; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/NullRuleCustomisationPolicy.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/NullRuleCustomisationPolicy.php new file mode 100644 index 0000000..e6753bb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/NullRuleCustomisationPolicy.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Config; + +/** + * EXPERIMENTAL: This feature is experimental and does not fall under the backward compatibility promise. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullRuleCustomisationPolicy implements RuleCustomisationPolicyInterface +{ + /** + * @internal + */ + public const VERSION_FOR_CACHE = 'null-policy'; + + public function getPolicyVersionForCache(): string + { + return self::VERSION_FOR_CACHE; + } + + public function getRuleCustomisers(): array + { + return []; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyAwareConfigInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyAwareConfigInterface.php new file mode 100644 index 0000000..5f9c511 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyAwareConfigInterface.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Config; + +use PhpCsFixer\ConfigInterface; + +/** + * EXPERIMENTAL: This feature is experimental and does not fall under the backward compatibility promise. + * + * @TODO 4.0 Include support for this in main ConfigInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface RuleCustomisationPolicyAwareConfigInterface extends ConfigInterface +{ + /** + * EXPERIMENTAL: This feature is experimental and does not fall under the backward compatibility promise. + * Registers a filter to be applied to fixers right before running them. + * + * @todo v4 Introduce it in main ConfigInterface + * + * @return $this + */ + public function setRuleCustomisationPolicy(?RuleCustomisationPolicyInterface $ruleCustomisationPolicy): ConfigInterface; + + /** + * EXPERIMENTAL: This feature is experimental and does not fall under the backward compatibility promise. + * Gets the filter to be applied to fixers right before running them. + * + * @todo v4 Introduce it in main ConfigInterface + */ + public function getRuleCustomisationPolicy(): ?RuleCustomisationPolicyInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyInterface.php new file mode 100644 index 0000000..fbef9fe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Config/RuleCustomisationPolicyInterface.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Config; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * EXPERIMENTAL: This feature is experimental and does not fall under the backward compatibility promise. + * + * @todo v3.999 replace \SplFileInfo with \Symfony\Component\Finder\SplFileInfo + * + * @phpstan-type _RuleCustomisationPolicyCallback \Closure(\SplFileInfo): (bool|FixerInterface) + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface RuleCustomisationPolicyInterface +{ + /** + * Returns a string that changes when the policy implementation changes in a way that + * would affect the cache validity. + * + * @example you may use the following snippet if your policy does not depend on any code outside of the file + * `return hash_file(\PHP_VERSION_ID >= 8_01_00 ? 'xxh128' : 'md5', __FILE__);` + * + * @return non-empty-string + */ + public function getPolicyVersionForCache(): string; + + /** + * Customise fixers for given files. + * + * Array keys are fixer names, values are closures that will be invoked before applying the fixer to a specific file. + * The closures receive the file as argument and must return: + * - true to apply the fixer as is to the file + * - false to skip applying the fixer to the file + * - a new fixer instance to apply a customised version of the fixer + * + * When PHP CS Fixer is about to start fixing files, it will check that the currently used fixers include at least + * all the fixers for which customisation rules are defined. If a customiser is defined for a fixer that is not currently applied, + * an exception will be thrown. + * This ensures that customisers are actually used for expected fixerswhich may be replaced by newer fixers in newer versions of PHP CS Fixer. + * Since fixer sets may change even in patch releases, this also means that your implementation of this interface may need to be updated accordingly, even in patch releases. + * So, we can't guarantee semver compatibility for Rule Customisation Policies. + * + * @example + * ``` + * [ + * 'array_syntax' => static function (\SplFileInfo $file) { + * if (str_ends_with($file->getPathname(), '/tests/foo.php')) { + * // Disable the fixer for the file tests/foo.php + * return false; + * } + * if (str_ends_with($file->getPathname(), '/bin/entrypoint')) { + * // For the file bin/entrypoint let's create a new fixer instance with a different configuration + * $fixer = new ArraySyntaxFixer(); + * $fixer->configure(['syntax' => 'long']); + * return $fixer; + * } + * // Keep the default configuration for other files + * return true; + * }, + * ] + * ``` + * + * @return array + */ + public function getRuleCustomisers(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php new file mode 100644 index 0000000..46f6a9e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php @@ -0,0 +1,192 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ConfigInterface +{ + /** @internal */ + public const PHP_VERSION_SYNTAX_SUPPORTED = '8.5'; + + /** + * Returns the path to the cache file. + * + * @return null|non-empty-string Returns null if not using cache + */ + public function getCacheFile(): ?string; + + /** + * Returns the custom fixers to use. + * + * @return list + */ + public function getCustomFixers(): array; + + /** + * Returns files to scan. + * + * @return iterable<\SplFileInfo> + */ + public function getFinder(): iterable; + + public function getFormat(): string; + + /** + * Returns true if progress should be hidden. + */ + public function getHideProgress(): bool; + + /** + * @return non-empty-string + */ + public function getIndent(): string; + + /** + * @return non-empty-string + */ + public function getLineEnding(): string; + + /** + * Returns the name of the configuration. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the configuration + */ + public function getName(): string; + + /** + * Get configured PHP executable, if any. + * + * @deprecated + * + * @TODO 4.0 remove me + */ + public function getPhpExecutable(): ?string; + + /** + * Check if it is allowed to run risky fixers. + */ + public function getRiskyAllowed(): bool; + + /** + * Get rules. + * + * Keys of array are names of fixers/sets, values are true/false. + * + * @return array|bool> + */ + public function getRules(): array; + + /** + * Returns true if caching should be enabled. + */ + public function getUsingCache(): bool; + + /** + * Adds a suite of custom fixers. + * + * Name of custom fixer should follow `VendorName/rule_name` convention. + * + * @param iterable $fixers + * + * @return $this + */ + public function registerCustomFixers(iterable $fixers): self; + + /** + * Sets the path to the cache file. + * + * @param non-empty-string $cacheFile + * + * @return $this + */ + public function setCacheFile(string $cacheFile): self; + + /** + * @param iterable<\SplFileInfo> $finder + * + * @return $this + */ + public function setFinder(iterable $finder): self; + + /** + * @return $this + */ + public function setFormat(string $format): self; + + /** + * @return $this + */ + public function setHideProgress(bool $hideProgress): self; + + /** + * @param non-empty-string $indent + * + * @return $this + */ + public function setIndent(string $indent): self; + + /** + * @param non-empty-string $lineEnding + * + * @return $this + */ + public function setLineEnding(string $lineEnding): self; + + /** + * Set PHP executable. + * + * @deprecated + * + * @TODO 4.0 remove me + * + * @return $this + */ + public function setPhpExecutable(?string $phpExecutable): self; + + /** + * Set if it is allowed to run risky fixers. + * + * @return $this + */ + public function setRiskyAllowed(bool $isRiskyAllowed): self; + + /** + * Set rules. + * + * Keys of array are names of fixers or sets. + * Value for set must be bool (turn it on or off). + * Value for fixer may be bool (turn it on or off) or array of configuration + * (turn it on and contains configuration for FixerInterface::configure method). + * + * @param array|bool> $rules + * + * @return $this + */ + public function setRules(array $rules): self; + + /** + * @return $this + */ + public function setUsingCache(bool $usingCache): self; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php new file mode 100644 index 0000000..e863bc4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; + +/** + * Exceptions of this type are thrown on misconfiguration of the Fixer. + * + * @internal + * + * @final Only internal extending this class is supported + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +class InvalidConfigurationException extends \InvalidArgumentException +{ + public function __construct(string $message, ?int $code = null, ?\Throwable $previous = null) + { + parent::__construct( + $message, + $code ?? FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, + $previous, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php new file mode 100644 index 0000000..1e1f5f0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; + +/** + * Exception thrown by Fixers on misconfiguration. + * + * @internal + * + * @final Only internal extending this class is supported + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +class InvalidFixerConfigurationException extends InvalidConfigurationException +{ + private string $fixerName; + + public function __construct(string $fixerName, string $message, ?\Throwable $previous = null) + { + parent::__construct( + \sprintf('[%s] %s', $fixerName, $message), + FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, + $previous, + ); + + $this->fixerName = $fixerName; + } + + public function getFixerName(): string + { + return $this->fixerName; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php new file mode 100644 index 0000000..4479039 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class InvalidForEnvFixerConfigurationException extends InvalidFixerConfigurationException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php new file mode 100644 index 0000000..437d4f1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RequiredFixerConfigurationException extends InvalidFixerConfigurationException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/UnresolvableAutoRuleSetConfigurationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/UnresolvableAutoRuleSetConfigurationException.php new file mode 100644 index 0000000..6f22dc2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/UnresolvableAutoRuleSetConfigurationException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class UnresolvableAutoRuleSetConfigurationException extends InvalidConfigurationException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php new file mode 100644 index 0000000..5b87ada --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php @@ -0,0 +1,250 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use PhpCsFixer\Console\Command\CheckCommand; +use PhpCsFixer\Console\Command\DescribeCommand; +use PhpCsFixer\Console\Command\FixCommand; +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Console\Command\InitCommand; +use PhpCsFixer\Console\Command\ListFilesCommand; +use PhpCsFixer\Console\Command\ListRulesCommand; +use PhpCsFixer\Console\Command\ListSetsCommand; +use PhpCsFixer\Console\Command\SelfUpdateCommand; +use PhpCsFixer\Console\Command\WorkerCommand; +use PhpCsFixer\Console\SelfUpdate\GithubClient; +use PhpCsFixer\Console\SelfUpdate\NewVersionChecker; +use PhpCsFixer\Future; +use PhpCsFixer\PharChecker; +use PhpCsFixer\Runner\Parallel\WorkerException; +use PhpCsFixer\ToolInfo; +use Symfony\Component\Console\Application as BaseApplication; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\CompleteCommand; +use Symfony\Component\Console\Command\DumpCompletionCommand; +use Symfony\Component\Console\Command\ListCommand; +use Symfony\Component\Console\Exception\CommandNotFoundException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Application extends BaseApplication +{ + public const NAME = 'PHP CS Fixer'; + public const VERSION = '3.95.15'; + public const VERSION_CODENAME = 'Adalbertus'; + + /** + * @readonly + */ + private ToolInfo $toolInfo; + + private ?Command $executedCommand = null; + + public function __construct() + { + parent::__construct(self::NAME, self::VERSION); + + $this->toolInfo = new ToolInfo(); + + // in alphabetical order + $this->add(new CheckCommand($this->toolInfo)); + $this->add(new DescribeCommand()); + $this->add(new FixCommand($this->toolInfo)); + $this->add(new InitCommand()); + $this->add(new ListFilesCommand($this->toolInfo)); + $this->add(new ListRulesCommand()); + $this->add(new ListSetsCommand()); + $this->add(new SelfUpdateCommand( + new NewVersionChecker(new GithubClient()), + $this->toolInfo, + new PharChecker(), + )); + $this->add(new WorkerCommand($this->toolInfo)); + } + + // polyfill for `add` method, as it is not available in Symfony 8.0 + public function add(Command $command): ?Command + { + if (method_exists($this, 'addCommand')) { // @phpstan-ignore-line + return $this->addCommand($command); + } + + return parent::add($command); // @phpstan-ignore-line + } + + public static function getMajorVersion(): int + { + return (int) explode('.', self::VERSION)[0]; + } + + public function doRun(InputInterface $input, OutputInterface $output): int + { + $stdErr = $output instanceof ConsoleOutputInterface + ? $output->getErrorOutput() + : ($input->hasParameterOption('--format', true) && 'txt' !== $input->getParameterOption('--format', null, true) ? null : $output); + + if (null !== $stdErr) { + $warningsDetector = new WarningsDetector($this->toolInfo); + $warningsDetector->detectOldVendor(); + $warningsDetector->detectOldMajor(); + + try { + $commandName = $this->getCommandName($input); + if (null === $commandName) { + throw new CommandNotFoundException('No command name found.'); + } + $command = $this->find($commandName); + + if (($command instanceof CheckCommand) || ($command instanceof FixCommand)) { + $warningsDetector->detectHigherPhpVersion(); + $warningsDetector->detectNonMonolithic(); + } + } catch (CommandNotFoundException $e) { + // no-op + } + + $warnings = $warningsDetector->getWarnings(); + + if (\count($warnings) > 0) { + foreach ($warnings as $warning) { + $stdErr->writeln(\sprintf($stdErr->isDecorated() ? '%s' : '%s', $warning)); + } + $stdErr->writeln(''); + } + } + + $result = parent::doRun($input, $output); + + if ( + null !== $stdErr + && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE + ) { + $triggeredDeprecations = Future::getTriggeredDeprecations(); + + if (\count($triggeredDeprecations) > 0) { + $stdErr->writeln(''); + $stdErr->writeln($stdErr->isDecorated() ? 'Detected deprecations in use (they will stop working in next major release):' : 'Detected deprecations in use (they will stop working in next major release):'); + foreach ($triggeredDeprecations as $deprecation) { + $stdErr->writeln(\sprintf('- %s', $deprecation)); + } + } + } + + return $result; + } + + /** + * @internal + */ + public static function getAbout(bool $decorated = false): string + { + $longVersion = \sprintf('%s %s', self::NAME, self::VERSION); + + // value of `$commitPlaceholderPossiblyEvaluated` will be changed during phar building, other value will not + $commitPlaceholderPossiblyEvaluated = '@git-commit@'; + $commitPlaceholder = implode('', ['@', 'git-commit@']); // do not replace with imploded value, as here we need to prevent phar builder to replace the placeholder + + $versionCommit = $commitPlaceholder !== $commitPlaceholderPossiblyEvaluated + ? substr($commitPlaceholderPossiblyEvaluated, 0, 7) // for phar builds + : ''; + + $about = implode('', [ + $longVersion, + $versionCommit ? \sprintf(' (%s)', $versionCommit) : '', // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + self::VERSION_CODENAME ? \sprintf(' %s', self::VERSION_CODENAME) : '', // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + ' by Fabien Potencier, Dariusz Ruminski and contributors.', + ]); + + if (false === $decorated) { + return strip_tags($about); + } + + return $about; + } + + /** + * @internal + */ + public static function getAboutWithRuntime(bool $decorated = false): string + { + $about = self::getAbout(true)."\nPHP runtime: ".\PHP_VERSION.''; + if (false === $decorated) { + return strip_tags($about); + } + + return $about; + } + + public function getLongVersion(): string + { + return self::getAboutWithRuntime(true); + } + + protected function getDefaultCommands(): array + { + return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()]; + } + + /** + * @throws \Throwable + */ + protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int + { + $this->executedCommand = $command; + + return parent::doRunCommand($command, $input, $output); + } + + protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void + { + // Since parallel analysis utilises child processes, and they have their own output, + // we need to capture the output of the child process to determine it there was an exception. + // Default render format is not machine-friendly, so we need to override it for `worker` command, + // in order to be able to easily parse exception data for further displaying on main process' side. + if ($this->executedCommand instanceof WorkerCommand) { + $output->writeln(WorkerCommand::ERROR_PREFIX.json_encode( + [ + 'class' => \get_class($e), + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'code' => $e->getCode(), + 'trace' => $e->getTraceAsString(), + ], + \JSON_THROW_ON_ERROR, + )); + + return; + } + + parent::doRenderThrowable($e, $output); + + if ($output->isVeryVerbose() && $e instanceof WorkerException) { + $output->writeln('Original trace from worker:'); + $output->writeln(''); + $output->writeln($e->getOriginalTraceAsString()); + $output->writeln(''); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php new file mode 100644 index 0000000..17eec10 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/CheckCommand.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Preg; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; + +/** + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'check', description: 'Checks if configured files/directories comply with configured rules.')] +final class CheckCommand extends FixCommand +{ + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct($toolInfo); + $this->setName('check'); + $this->setDescription('Checks if configured files/directories comply with configured rules.'); + } + + public function getHelp(): string + { + return Preg::replace('@\v\V*--dry-run\V*\v@', '', parent::getHelp()); + } + + protected function configure(): void + { + parent::configure(); + + $this->setDefinition([ + ...array_values($this->getDefinition()->getArguments()), + ...array_values(array_filter( + $this->getDefinition()->getOptions(), + static fn (InputOption $option): bool => 'dry-run' !== $option->getName(), + )), + ]); + } + + protected function isDryRun(InputInterface $input): bool + { + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php new file mode 100644 index 0000000..ca27c8b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php @@ -0,0 +1,769 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\Console\Application; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Documentation\DocumentationTag; +use PhpCsFixer\Documentation\DocumentationTagGenerator; +use PhpCsFixer\Documentation\DocumentationTagType; +use PhpCsFixer\Documentation\FixerDocumentGenerator; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerConfiguration\AliasedFixerOption; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; +use PhpCsFixer\FixerDefinition\CodeSampleInterface; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\Utils; +use PhpCsFixer\WordMatcher; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\TreeHelper; +use Symfony\Component\Console\Helper\TreeNode; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'describe', description: 'Describe rule / ruleset.')] +final class DescribeCommand extends Command +{ + private const SET_ALIAS_TO_DESCRIBE_CONFIG = '@'; + private const SET_ALIAS_TO_DESCRIBE_RULES_WITHOUT_SET = '@-'; + + /** + * @var ?list + */ + private ?array $setNames = null; + + private FixerFactory $fixerFactory; + + /** + * @var null|array + */ + private ?array $fixers = null; + + public function __construct(?FixerFactory $fixerFactory = null) + { + parent::__construct('describe'); + $this->setDescription('Describe rule / ruleset.'); + + if (null === $fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + } + + $this->fixerFactory = $fixerFactory; + } + + protected function configure(): void + { + $this->setDefinition( + [ + new InputArgument('name', InputArgument::OPTIONAL, 'Name of rule / set.', null, fn () => array_merge($this->getSetNames(), array_keys($this->getFixers()))), + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'), + new InputOption('expand', '', InputOption::VALUE_NONE, 'Shall nested sets be expanded into nested rules.'), + new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats (txt, tree).', 'txt', ['txt', 'tree']), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + if ($output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln(Application::getAboutWithRuntime(true)); + } + + $resolver = new ConfigurationResolver( + new Config(), + ['config' => $input->getOption('config')], + getcwd(), // @phpstan-ignore argument.type + new ToolInfo(), + ); + + $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers()); + + /** @var ?string $name */ + $name = $input->getArgument('name'); + $expand = $input->getOption('expand'); + $format = $input->getOption('format'); + + if (null === $name) { + if (false === $input->isInteractive()) { + throw new RuntimeException('Not enough arguments (missing: "name") when not running interactively.'); + } + + $io = new SymfonyStyle($input, $output); + $shallDescribeConfigInUse = 'yes' === $io->choice( + 'Do you want to describe used configuration? (alias:`@`', + ['yes', 'no'], + 'yes', + ); + if ($shallDescribeConfigInUse) { + $name = self::SET_ALIAS_TO_DESCRIBE_CONFIG; + } else { + $name = $io->choice( + 'Please select rule / set to describe', + array_merge($this->getSetNames(), array_keys($this->getFixers())), + ); + } + } + + if ('tree' === $format) { + if (!str_starts_with($name, '@')) { + throw new \InvalidArgumentException( + 'The "--format=tree" option is available only when describing a set (name starting with "@").', + ); + } + if (!class_exists(TreeHelper::class)) { + throw new \RuntimeException('The "--format=tree" option requires symfony/console 7.3+.'); + } + } + + if (!str_starts_with($name, '@')) { + if (true === $expand) { + throw new \InvalidArgumentException( + 'The "--expand" option is available only when describing a set (name starting with "@").', + ); + } + } + + try { + if (str_starts_with($name, '@')) { + $this->describeSet($input, $output, $name, $resolver); + + return 0; + } + + $this->describeRule($output, $name); + } catch (DescribeNameNotFoundException $e) { + $matcher = new WordMatcher( + 'set' === $e->getType() ? $this->getSetNames() : array_keys($this->getFixers()), + ); + + $alternative = $matcher->match($name); + + $this->describeList($output, $e->getType()); + + throw new \InvalidArgumentException(\sprintf( + '%s "%s" not found.%s', + ucfirst($e->getType()), + $name, + null === $alternative ? '' : ' Did you mean "'.$alternative.'"?', + )); + } + + return 0; + } + + private function describeRule(OutputInterface $output, string $name): void + { + $fixers = $this->getFixers(); + + if (!isset($fixers[$name])) { + throw new DescribeNameNotFoundException($name, 'rule'); + } + + $fixer = $fixers[$name]; + + $definition = $fixer->getDefinition(); + + $output->writeln(\sprintf('Description of the `%s` rule.', $name)); + $output->writeln(''); + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $output->writeln(\sprintf('Fixer class: %s.', \get_class($fixer))); + $output->writeln(''); + } + + $output->writeln($definition->getSummary()); + + $description = $definition->getDescription(); + + if (null !== $description) { + $output->writeln($description); + } + + $output->writeln(''); + + $tags = DocumentationTagGenerator::analyseRule($fixer); + + foreach ($tags as $tag) { + if (DocumentationTagType::DEPRECATED === $tag->type) { + Future::triggerDeprecation(new \RuntimeException(str_replace( + '`', + '"', + \sprintf( + '%s%s', + str_replace('This rule', \sprintf('Rule "%s"', $name), $tag->title), + null !== $tag->description ? '. '.$tag->description : '', + ), + ))); + } elseif (DocumentationTagType::CONFIGURABLE === $tag->type) { + continue; // skip, handled later + } + + $output->writeln(\sprintf('%s', $tag->title)); + $tagDescription = $tag->description; + + if (null !== $tagDescription) { + $tagDescription = Preg::replace('/(`[^`]+`)/', '$1', $tagDescription); + $output->writeln($tagDescription); + } + + $output->writeln(''); + } + + if ($fixer instanceof ConfigurableFixerInterface) { + $configurationDefinition = $fixer->getConfigurationDefinition(); + $options = $configurationDefinition->getOptions(); + + $output->writeln(\sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's')); + + foreach ($options as $option) { + $line = '* '.OutputFormatter::escape($option->getName()).''; + $allowed = HelpCommand::getDisplayableAllowedValues($option); + + if (null === $allowed) { + $allowedTypes = $option->getAllowedTypes(); + if (null !== $allowedTypes) { + $allowed = array_map( + static fn (string $type): string => ''.$type.'', + $allowedTypes, + ); + } + } else { + $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset + ? 'a subset of '.Utils::toString($value->getAllowedValues()).'' + : ''.Utils::toString($value).'', $allowed); + } + + if (null !== $allowed) { + $line .= ' ('.Utils::naturalLanguageJoin($allowed, '').')'; + } + + $description = Preg::replace('/(`.+?`)/', '$1', OutputFormatter::escape($option->getDescription())); + $line .= ': '.lcfirst(Preg::replace('/\.$/', '', $description)).'; '; + + if ($option->hasDefault()) { + $line .= \sprintf( + 'defaults to %s', + Utils::toString($option->getDefault()), + ); + } else { + $line .= 'required'; + } + + if ($option instanceof DeprecatedFixerOption) { + $line .= '. DEPRECATED: '.Preg::replace( + '/(`.+?`)/', + '$1', + OutputFormatter::escape(lcfirst($option->getDeprecationMessage())), + ); + } + + if ($option instanceof AliasedFixerOption) { + $line .= '; DEPRECATED alias: '.$option->getAlias().''; + } + + $output->writeln($line); + } + + $output->writeln(''); + } + + $codeSamples = array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample): bool { + if ($codeSample instanceof VersionSpecificCodeSampleInterface) { + return $codeSample->isSuitableFor(\PHP_VERSION_ID); + } + + return true; + }); + + if (0 === \count($definition->getCodeSamples())) { + $output->writeln([ + 'Fixing examples are not available for this rule.', + '', + ]); + } elseif (0 === \count($codeSamples)) { + $output->writeln([ + 'Fixing examples cannot be demonstrated on the current PHP version.', + '', + ]); + } else { + $output->writeln('Fixing examples:'); + + $differ = new FullDiffer(); + $diffFormatter = new DiffConsoleFormatter( + $output->isDecorated(), + \sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + \PHP_EOL, + \PHP_EOL, + ), + ); + + foreach ($codeSamples as $index => $codeSample) { + $old = $codeSample->getCode(); + $tokens = Tokens::fromCode($old); + + $configuration = $codeSample->getConfiguration(); + + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($configuration ?? []); + } + + $file = $codeSample instanceof FileSpecificCodeSampleInterface + ? $codeSample->getSplFileInfo() + : new StdinFileInfo(); + + $fixer->fix($file, $tokens); + + $diff = $differ->diff($old, $tokens->generateCode()); + + if ($fixer instanceof ConfigurableFixerInterface) { + if (null === $configuration) { + $output->writeln(\sprintf(' * Example #%d. Fixing with the default configuration.', $index + 1)); + } else { + $output->writeln(\sprintf(' * Example #%d. Fixing with configuration: %s.', $index + 1, Utils::toString($codeSample->getConfiguration()))); + } + } else { + $output->writeln(\sprintf(' * Example #%d.', $index + 1)); + } + + $output->writeln([$diffFormatter->format($diff, ' %s'), '']); + } + } + + $ruleSetConfigs = FixerDocumentGenerator::getSetsOfRule($name); + + if ([] !== $ruleSetConfigs) { + ksort($ruleSetConfigs); + $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; + $output->writeln("The fixer is part of the following rule set{$plural}:"); + + $ruleSetDefinitions = RuleSets::getSetDefinitions(); + + foreach ($ruleSetConfigs as $set => $config) { + \assert(isset($ruleSetDefinitions[$set])); + $ruleSetDefinition = $ruleSetDefinitions[$set]; + + if ($ruleSetDefinition instanceof AutomaticRuleSetDefinitionInterface) { + continue; + } + + $deprecatedDesc = ($ruleSetDefinition instanceof DeprecatedRuleSetDefinitionInterface) ? ' *(deprecated)*' : ''; + if (null !== $config) { + $output->writeln(\sprintf('* %s with config: %s', $set.$deprecatedDesc, Utils::toString($config))); + } else { + $output->writeln(\sprintf('* %s with default config', $set.$deprecatedDesc)); + } + } + + $output->writeln(''); + } + } + + private function describeSet(InputInterface $input, OutputInterface $output, string $name, ConfigurationResolver $resolver): void + { + if ( + !\in_array($name, [self::SET_ALIAS_TO_DESCRIBE_CONFIG, self::SET_ALIAS_TO_DESCRIBE_RULES_WITHOUT_SET], true) + && !\in_array($name, $this->getSetNames(), true)) { + throw new DescribeNameNotFoundException($name, 'set'); + } + + if (self::SET_ALIAS_TO_DESCRIBE_CONFIG === $name) { + $aliasedRuleSetDefinition = $this->createRuleSetDefinition( + null, + [], + [ + 'getDescription' => null === $resolver->getConfigFile() ? 'Default rules, no config file.' : 'Rules defined in used config.', + 'getName' => \sprintf('@ - %s', $resolver->getConfig()->getName()), + 'getRules' => $resolver->getConfig()->getRules(), + 'isRisky' => $resolver->getRiskyAllowed(), + ], + ); + } elseif (self::SET_ALIAS_TO_DESCRIBE_RULES_WITHOUT_SET === $name) { + $rulesWithoutSet = array_filter( + $this->getFixers(), + static fn (string $name): bool => [] === FixerDocumentGenerator::getSetsOfRule($name), + \ARRAY_FILTER_USE_KEY, + ); + + $aliasedRuleSetDefinition = $this->createRuleSetDefinition( + null, + [], + [ + 'getDescription' => 'Rules that are not part of any set.', + 'getName' => '@- - rules without set', + 'getRules' => array_combine( + array_map( + static fn (FixerInterface $fixer): string => $fixer->getName(), + $rulesWithoutSet, + ), + array_fill(0, \count($rulesWithoutSet), true), + ), + 'isRisky' => array_any( + $rulesWithoutSet, + static fn (FixerInterface $fixer): bool => $fixer->isRisky(), + ), + ], + ); + } + + $ruleSetDefinitions = RuleSets::getSetDefinitions(); + $ruleSetDefinition = $aliasedRuleSetDefinition ?? $ruleSetDefinitions[$name]; + $fixers = $this->getFixers(); + + if (true === $input->getOption('expand')) { + $ruleSetDefinition = $this->createRuleSetDefinition($ruleSetDefinition, ['expand'], []); + } else { + $output->writeln("You may the '--expand' option to see nested sets expanded into nested rules."); + } + + $output->writeln(\sprintf('Description of the `%s` set.', $ruleSetDefinition->getName())); + $output->writeln(''); + + $output->writeln($this->replaceRstLinks($ruleSetDefinition->getDescription())); + $output->writeln(''); + + $tags = DocumentationTagGenerator::analyseRuleSet($ruleSetDefinition); + + foreach ($tags as $tag) { + if (DocumentationTagType::DEPRECATED === $tag->type) { + Future::triggerDeprecation(new \RuntimeException(str_replace( + '`', + '"', + \sprintf( + '%s%s', + str_replace('This rule set', \sprintf('Rule set "%s"', $name), $tag->title), + null !== $tag->description ? '. '.$tag->description : '', + ), + ))); + } + + $output->writeln(\sprintf('%s', $tag->title)); + $tagDescription = $tag->description; + + if (null !== $tagDescription) { + $tagDescription = Preg::replace('/(`[^`]+`)/', '$1', $tagDescription); + $output->writeln($tagDescription); + } + + $output->writeln(''); + } + + if ('tree' === $input->getOption('format')) { + $this->describeSetContentAsTree($output, $ruleSetDefinition, $ruleSetDefinitions, $fixers); + } else { + $this->describeSetContentAsTxt($output, $ruleSetDefinition, $ruleSetDefinitions, $fixers); + } + } + + /** + * @param array $ruleSetDefinitions + * @param array $fixers + */ + private function createTreeNode(RuleSetDefinitionInterface $ruleSetDefinition, array $ruleSetDefinitions, array $fixers): TreeNode + { + $tags = DocumentationTagGenerator::analyseRuleSet($ruleSetDefinition); + $extra = [] !== $tags + ? ' '.implode(' ', array_map( + static fn (DocumentationTag $tag): string => "{$tag->type}", + $tags, + )) + : ''; + + $node = new TreeNode($ruleSetDefinition->getName().$extra); + + $rules = $ruleSetDefinition->getRules(); + $rulesKeys = array_keys($rules); + natcasesort($rulesKeys); + + foreach ($rulesKeys as $rule) { + \assert(isset($rules[$rule])); + $config = $rules[$rule]; + if (str_starts_with($rule, '@')) { + \assert(isset($ruleSetDefinitions[$rule])); + $child = $this->createTreeNode($ruleSetDefinitions[$rule], $ruleSetDefinitions, $fixers); + } else { + \assert(isset($fixers[$rule])); + $fixer = $fixers[$rule]; + $tags = DocumentationTagGenerator::analyseRule($fixer); + $extra = [] !== $tags + ? ' '.implode(' ', array_map( + static fn (DocumentationTag $tag): string => "{$tag->type}", + $tags, + )) + : ''; + if (false === $config) { + $extra = \sprintf(' | Configuration: %s', Utils::toString($config)); + } elseif (true !== $config) { + $extra = \sprintf(' | Configuration: %s', Utils::toString($config)); + } + $child = new TreeNode($rule.$extra); + } + $node->addChild($child); + } + + return $node; + } + + /** + * @param array $ruleSetDefinitions + * @param array $fixers + */ + private function describeSetContentAsTree(OutputInterface $output, RuleSetDefinitionInterface $ruleSetDefinition, array $ruleSetDefinitions, array $fixers): void + { + $io = new SymfonyStyle( + new ArrayInput([]), + $output, + ); + + $root = $this->createTreeNode($ruleSetDefinition, $ruleSetDefinitions, $fixers); + $tree = TreeHelper::createTree($io, $root); + $tree->render(); + } + + /** + * @param array $ruleSetDefinitions + * @param array $fixers + */ + private function describeSetContentAsTxt(OutputInterface $output, RuleSetDefinitionInterface $ruleSetDefinition, array $ruleSetDefinitions, array $fixers): void + { + $help = ''; + + foreach ($ruleSetDefinition->getRules() as $rule => $config) { + if (str_starts_with($rule, '@')) { + \assert(isset($ruleSetDefinitions[$rule])); + $set = $ruleSetDefinitions[$rule]; + $tags = DocumentationTagGenerator::analyseRuleSet($set); + $help .= \sprintf( + " * %s%s%s\n | %s\n\n", + $rule, + [] !== $tags ? ' ' : '', + implode(' ', array_map( + static fn (DocumentationTag $tag): string => "{$tag->type}", + $tags, + )), + $this->replaceRstLinks($set->getDescription()), + ); + + continue; + } + + \assert(isset($fixers[$rule])); + $fixer = $fixers[$rule]; + $tags = DocumentationTagGenerator::analyseRule($fixer); + + $definition = $fixer->getDefinition(); + $help .= \sprintf( + " * %s%s%s\n | %s\n%s\n", + $rule, + [] !== $tags ? ' ' : '', + implode(' ', array_map( + static fn (DocumentationTag $tag): string => "{$tag->type}", + $tags, + )), + $definition->getSummary(), + true !== $config ? \sprintf(" | Configuration: %s\n", Utils::toString($config)) : '', + ); + } + + $output->write($help); + } + + /** + * @return array + */ + private function getFixers(): array + { + if (null !== $this->fixers) { + return $this->fixers; + } + + $fixers = []; + + foreach ($this->fixerFactory->getFixers() as $fixer) { + $fixers[$fixer->getName()] = $fixer; + } + + $this->fixers = $fixers; + ksort($this->fixers); + + return $this->fixers; + } + + /** + * @return list + */ + private function getSetNames(): array + { + if (null !== $this->setNames) { + return $this->setNames; + } + + $this->setNames = RuleSets::getSetDefinitionNames(); + + return $this->setNames; + } + + /** + * @param string $type 'rule'|'set' + */ + private function describeList(OutputInterface $output, string $type): void + { + if ($output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) { + return; + } + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'set' === $type) { + $output->writeln('Defined sets:'); + + $items = $this->getSetNames(); + foreach ($items as $item) { + $output->writeln(\sprintf('* %s', $item)); + } + } + + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE || 'rule' === $type) { + $output->writeln('Defined rules:'); + + $items = array_keys($this->getFixers()); + foreach ($items as $item) { + $output->writeln(\sprintf('* %s', $item)); + } + } + } + + private function replaceRstLinks(string $content): string + { + return Preg::replaceCallback( + '/(`[^<]+<[^>]+>`_)/', + static fn (array $matches) => Preg::replaceCallback( + '/`(.*)<(.*)>`_/', + static fn (array $matches): string => $matches[1].'('.$matches[2].')', + $matches[1], + ), + $content, + ); + } + + /** + * @param list<'expand'> $adjustments + * @param array{getDescription?: string, getName?: string, getRules?: array|bool>, isRisky?: bool} $overrides + */ + private function createRuleSetDefinition(?RuleSetDefinitionInterface $ruleSetDefinition, array $adjustments, array $overrides): RuleSetDefinitionInterface + { + return new class($ruleSetDefinition, $adjustments, $overrides) implements RuleSetDefinitionInterface { + private ?RuleSetDefinitionInterface $original; + + /** @var list<'expand'> */ + private array $adjustments; + + /** @var array{getDescription?: string, getName?: string, getRules?: array|bool>, isRisky?: bool} */ + private array $overrides; + + /** + * @param list<'expand'> $adjustments + * @param array{getDescription?: string, getName?: string, getRules?: array|bool>, isRisky?: bool} $overrides + */ + public function __construct( + ?RuleSetDefinitionInterface $original, + array $adjustments, + array $overrides + ) { + $this->original = $original; + $this->adjustments = $adjustments; + $this->overrides = $overrides; + } + + public function getDescription(): string + { + return $this->overrides[__FUNCTION__] + ?? (null !== $this->original ? $this->original->{__FUNCTION__}() : 'unknown description'); // @phpstan-ignore method.dynamicName + } + + public function getName(): string + { + $value = $this->overrides[__FUNCTION__] + ?? (null !== $this->original ? $this->original->{__FUNCTION__}() : 'unknown name'); // @phpstan-ignore method.dynamicName + + if (\in_array('expand', $this->adjustments, true)) { + $value .= ' (expanded)'; + } + + return $value; + } + + public function getRules(): array + { + $value = $this->overrides[__FUNCTION__] + ?? (null !== $this->original ? $this->original->{__FUNCTION__}() : null); // @phpstan-ignore method.dynamicName + + if (null === $value) { + throw new \LogicException('Cannot get rules from unknown original rule set and missing overrides.'); + } + + if (\in_array('expand', $this->adjustments, true)) { + $value = (new RuleSet($value))->getRules(); + } + + return $value; + } + + public function isRisky(): bool + { + $value = $this->overrides[__FUNCTION__] + ?? (null !== $this->original ? $this->original->{__FUNCTION__}() : null); // @phpstan-ignore method.dynamicName + + if (null === $value) { + throw new \LogicException('Cannot get isRisky from unknown original rule set and missing overrides.'); + } + + return $value; + } + }; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php new file mode 100644 index 0000000..af63896 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DescribeNameNotFoundException extends \InvalidArgumentException +{ + private string $name; + + /** + * 'rule'|'set'. + */ + private string $type; + + public function __construct(string $name, string $type) + { + $this->name = $name; + $this->type = $type; + + parent::__construct(); + } + + public function getName(): string + { + return $this->name; + } + + public function getType(): string + { + return $this->type; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php new file mode 100644 index 0000000..a3c183b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php @@ -0,0 +1,460 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Application; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Console\Output\ErrorOutput; +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\Console\Output\Progress\ProgressOutputFactory; +use PhpCsFixer\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReporterFactory; +use PhpCsFixer\Console\Report\FixReport\ReportSummary; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Runner\Event\FileProcessed; +use PhpCsFixer\Runner\Runner; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Console\Terminal; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0: mark as final + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'fix', description: 'Fixes a directory or a file.')] +/* final */ class FixCommand extends Command +{ + private EventDispatcherInterface $eventDispatcher; + + private ErrorsManager $errorsManager; + + private Stopwatch $stopwatch; + + private ConfigInterface $defaultConfig; + + private ToolInfoInterface $toolInfo; + + private ProgressOutputFactory $progressOutputFactory; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct('fix'); + $this->setDescription('Fixes a directory or a file.'); + + $this->eventDispatcher = new EventDispatcher(); + $this->errorsManager = new ErrorsManager(); + $this->stopwatch = new Stopwatch(); + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + $this->progressOutputFactory = new ProgressOutputFactory(); + } + + /** + * {@inheritdoc} + * + * Override here to only generate the help copy when used. + */ + public function getHelp(): string + { + return <<<'EOF' + The %command.name% command tries to %command.name% as much coding standards + problems as possible on a given file or files in a given directory and its subdirectories: + + $ php %command.full_name% /path/to/dir + $ php %command.full_name% /path/to/file + + By default --path-mode is set to `override`, which means, that if you specify the path to a file or a directory via + command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use --path-mode=intersection + to merge paths from the config file and from the argument: + + $ php %command.full_name% --path-mode=intersection /path/to/dir + + The --format option for the output format. Supported formats are `@auto` (default one on v4+), `txt` (default one on v3), `json`, `xml`, `checkstyle`, `junit` and `gitlab`. + + * `@auto` aims to auto-select best reporter for given CI or local execution (resolution into best format is outside of BC promise and is future-ready) + * `gitlab` for GitLab + * `@auto,{format}` takes `@auto` under CI, and {format} otherwise + + NOTE: the output for the following formats are generated in accordance with schemas + + * `checkstyle` follows the common `"checkstyle" XML schema `_ + * `gitlab` follows the `codeclimate JSON schema `_ + * `json` follows the `own JSON schema `_ + * `junit` follows the `JUnit XML schema from Jenkins `_ + * `xml` follows the `own XML schema `_ + + The --quiet Do not output any message. + + The --verbose option will show the applied rules. When using the `txt` format it will also display progress notifications. + + NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose + + * `-v`: verbose + * `-vv`: very verbose + * `-vvv`: debug + + EOF. /* @TODO: 4.0 - change to @PER */ <<<'EOF' + + The --rules option allows to explicitly select rules to use, + overriding the default PSR-12 or your own project config: + + $ php %command.full_name% . --rules=line_ending,full_opening_tag,indentation_type + + You can also exclude the rules you don't want by placing a dash in front of the rule name, like -name_of_fixer. + + $ php %command.full_name% . --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison + + Complete configuration for rules can be supplied using a `json` formatted string as well. + + $ php %command.full_name% . --rules='{"concat_space": {"spacing": "none"}}' + + The --dry-run flag will run the fixer without making changes to your files. + + The --sequential flag will enforce sequential analysis even if parallel config is provided. + + The --diff flag can be used to let the fixer output all the changes it makes. + + The --allow-risky option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file. + A rule is considered risky if it could change code behaviour. By default no risky rules are run. + + The --stop-on-violation flag stops the execution upon first file that needs to be fixed. + + The --show-progress option allows you to choose the way process progress is rendered: + + * none: disables progress output; + * dots: multiline progress output with number of files and percentage on each line. + * bar: single line progress output with number of files and calculated percentage. + + If the option is not provided, it defaults to bar unless a config file that disables output is used, in which case it defaults to none. This option has no effect if the verbosity of the command is less than verbose. + + $ php %command.full_name% --verbose --show-progress=dots + + By using --using-cache option with `yes` or `no` you can set if the caching + mechanism should be used. + + The command can also read from standard input, in which case it won't + automatically fix anything: + + $ cat foo.php | php %command.full_name% --diff - + + Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that + would be default in next MAJOR release and to forbid using deprecated configuration: + + $ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff + + Exit code + --------- + + Exit code of the `%command.name%` command is built using following bit flags: + + * 0 - OK. + * 1 - General error (or PHP minimal requirement not matched). + * 4 - Some files have invalid syntax (only in dry-run mode). + * 8 - Some files need fixing (only in dry-run mode). + * 16 - Configuration error of the application. + * 32 - Configuration error of a Fixer. + * 64 - Exception raised within the application. + + EOF; + } + + protected function configure(): void + { + $reporterFactory = new ReporterFactory(); + $reporterFactory->registerBuiltInReporters(); + $formats = $reporterFactory->getFormats(); + array_unshift($formats, '@auto', '@auto,txt'); + + $progressOutputTypes = ProgressOutputType::all(); + + $this->setDefinition( + [ + new InputArgument('path', InputArgument::IS_ARRAY, 'The path(s) that rules will be run against (each path can be a file or directory).'), + new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Specify path mode (%s).', ConfigurationResolver::PATH_MODE_VALUES), ConfigurationResolver::PATH_MODE_OVERRIDE, ConfigurationResolver::PATH_MODE_VALUES), + new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Are risky fixers allowed (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES), + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'), + new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'), + new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.', null, static function () { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixers = array_map(static fn (FixerInterface $fixer) => $fixer->getName(), $fixerFactory->getFixers()); + + return array_merge(RuleSets::getSetDefinitionNames(), $fixers); + }), + new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should cache be used (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES), + new InputOption('allow-unsupported-php-version', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should the command refuse to run on unsupported PHP version (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES), + new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'), + new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'), + new InputOption('format', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('To output results in other formats (%s).', $formats), null, $formats), + new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'), + new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Type of progress indicator (%s).', $progressOutputTypes), null, $progressOutputTypes), + new InputOption('sequential', '', InputOption::VALUE_NONE, 'Enforce sequential analysis.'), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $verbosity = $output->getVerbosity(); + + $passedConfig = $input->getOption('config'); + $passedRules = $input->getOption('rules'); + + if (null !== $passedConfig && ConfigurationResolver::IGNORE_CONFIG_FILE !== $passedConfig && null !== $passedRules) { + throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.'); + } + + $resolver = new ConfigurationResolver( + $this->defaultConfig, + [ + 'allow-risky' => $input->getOption('allow-risky'), + 'config' => $passedConfig, + 'dry-run' => $this->isDryRun($input), + 'rules' => $passedRules, + 'path' => $input->getArgument('path'), + 'path-mode' => $input->getOption('path-mode'), + 'using-cache' => $input->getOption('using-cache'), + 'allow-unsupported-php-version' => $input->getOption('allow-unsupported-php-version'), + 'cache-file' => $input->getOption('cache-file'), + 'format' => $input->getOption('format'), + 'diff' => $input->getOption('diff'), + 'stop-on-violation' => $input->getOption('stop-on-violation'), + 'verbosity' => $verbosity, + 'show-progress' => $input->getOption('show-progress'), + 'sequential' => $input->getOption('sequential'), + ], + getcwd(), // @phpstan-ignore argument.type + $this->toolInfo, + ); + + $reporter = $resolver->getReporter(); + + $stdErr = $output instanceof ConsoleOutputInterface + ? $output->getErrorOutput() + : ('txt' === $reporter->getFormat() ? $output : null); + + if (null !== $stdErr) { + $stdErr->writeln(Application::getAboutWithRuntime(true)); + + if (version_compare(\PHP_VERSION, ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED.'.99', '>')) { + $message = \sprintf( + 'PHP CS Fixer currently supports PHP syntax only up to PHP %s, current PHP version: %s.', + ConfigInterface::PHP_VERSION_SYNTAX_SUPPORTED, + \PHP_VERSION, + ); + + if (!$resolver->getUnsupportedPhpVersionAllowed()) { + $message .= ' Add `Config::setUnsupportedPhpVersionAllowed(true)` to allow executions on unsupported PHP versions. Such execution may be unstable and you may experience code modified in a wrong way.'; + $stdErr->writeln(\sprintf( + $stdErr->isDecorated() ? '%s' : '%s', + $message, + )); + + return 1; + } + $message .= ' Execution may be unstable. You may experience code modified in a wrong way. Please report such cases at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. Remove Config::setUnsupportedPhpVersionAllowed(true) to allow executions only on supported PHP versions.'; + $stdErr->writeln(\sprintf( + $stdErr->isDecorated() ? '%s' : '%s', + $message, + )); + } + + $configFile = $resolver->getConfigFile(); + $stdErr->writeln(\sprintf('Loaded config %s%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"')); + + if (null === $configFile && ConfigurationResolver::IGNORE_CONFIG_FILE !== $passedConfig && null === $passedRules) { + if (false === $input->isInteractive()) { + $stdErr->writeln( + \sprintf( + $stdErr->isDecorated() ? '%s' : '%s', + 'No config file found. Please create one using `php-cs-fixer init`.', + ), + ); + } else { + $io = new SymfonyStyle($input, $stdErr); + $shallCreateConfigFile = 'yes' === $io->choice( + 'Do you want to create the config file?', + ['yes', 'no'], + 'yes', + ); + if ($shallCreateConfigFile) { + $returnCode = $this->getApplication()->doRun( + new ArrayInput([ + 'command' => 'init', + ]), + $output, + ); + $stdErr->writeln('Config file created, re-run the command to put it in action.'); + + return $returnCode; + } + } + } + + $isParallel = $resolver->getParallelConfig()->getMaxProcesses() > 1; + + $stdErr->writeln(\sprintf( + 'Running analysis on %d core%s.', + $resolver->getParallelConfig()->getMaxProcesses(), + $isParallel ? \sprintf( + 's with %d file%s per process', + $resolver->getParallelConfig()->getFilesPerProcess(), + $resolver->getParallelConfig()->getFilesPerProcess() > 1 ? 's' : '', + ) : ' sequentially', + )); + + if ($resolver->getUsingCache()) { + $cacheFile = $resolver->getCacheFile(); + + if (is_file($cacheFile)) { + $stdErr->writeln(\sprintf('Using cache file "%s".', $cacheFile)); + } + } + } + + $finder = new \ArrayIterator(array_filter( + iterator_to_array($resolver->getFinder()), + static fn (\SplFileInfo $fileInfo) => false !== $fileInfo->getRealPath(), + )); + + if (null !== $stdErr) { + if ($resolver->configFinderIsOverridden()) { + $stdErr->writeln( + \sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Paths from configuration have been overridden by paths provided as command arguments.'), + ); + } + + if ($resolver->configRulesAreOverridden()) { + $stdErr->writeln( + \sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Rules from configuration have been overridden by rules provided as command argument.'), + ); + } + } + + $progressType = $resolver->getProgressType(); + $progressOutput = $this->progressOutputFactory->create( + $progressType, + new OutputContext( + $stdErr, + (new Terminal())->getWidth(), + \count($finder), + ), + ); + + $runner = new Runner( + $finder, + $resolver->getFixers(), + $resolver->getDiffer(), + ProgressOutputType::NONE !== $progressType ? $this->eventDispatcher : null, + $this->errorsManager, + $resolver->getLinter(), + $resolver->isDryRun(), + $resolver->getCacheManager(), + $resolver->getDirectory(), + $resolver->shouldStopOnViolation(), + $resolver->getParallelConfig(), + $input, + $resolver->getConfigFile(), + $resolver->getRuleCustomisationPolicy(), + ); + + $this->eventDispatcher->addListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']); + $this->stopwatch->start('fixFiles'); + $changed = $runner->fix(); + $this->stopwatch->stop('fixFiles'); + $this->eventDispatcher->removeListener(FileProcessed::NAME, [$progressOutput, 'onFixerFileProcessed']); + + $progressOutput->printLegend(); + + $fixEvent = $this->stopwatch->getEvent('fixFiles'); + + $reportSummary = new ReportSummary( + $changed, + \count($finder), + (int) $fixEvent->getDuration(), // ignore microseconds fraction + memory_get_peak_usage(true) + $runner->getWorkersMemoryUsage(), + OutputInterface::VERBOSITY_VERBOSE <= $verbosity, + $resolver->isDryRun(), + $output->isDecorated(), + ); + + $output->isDecorated() + ? $output->write($reporter->generate($reportSummary)) + : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW); + + $invalidErrors = $this->errorsManager->getInvalidErrors(); + $exceptionErrors = $this->errorsManager->getExceptionErrors(); + $lintErrors = $this->errorsManager->getLintErrors(); + + if (null !== $stdErr) { + $errorOutput = new ErrorOutput($stdErr); + + if (\count($invalidErrors) > 0) { + $errorOutput->listErrors('linting before fixing', $invalidErrors); + } + + if (\count($exceptionErrors) > 0) { + $errorOutput->listErrors('fixing', $exceptionErrors); + if ($isParallel) { + $stdErr->writeln('To see details of the error(s), re-run the command with `--sequential -vvv [file]`'); + } + } + + if (\count($lintErrors) > 0) { + $errorOutput->listErrors('linting after fixing', $lintErrors); + } + } + + $exitStatusCalculator = new FixCommandExitStatusCalculator(); + + return $exitStatusCalculator->calculate( + $resolver->isDryRun(), + \count($changed) > 0, + \count($invalidErrors) > 0, + \count($exceptionErrors) > 0, + \count($lintErrors) > 0, + ); + } + + protected function isDryRun(InputInterface $input): bool + { + return $input->getOption('dry-run'); // @phpstan-ignore symfonyConsole.optionNotFound (Because PHPStan doesn't recognise the method is overridden in the child class and this parameter is _not_ used in the child class.) + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php new file mode 100644 index 0000000..233ba75 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixCommandExitStatusCalculator +{ + // Exit status 1 is reserved for environment constraints not matched. + public const EXIT_STATUS_FLAG_HAS_INVALID_FILES = 4; + public const EXIT_STATUS_FLAG_HAS_CHANGED_FILES = 8; + public const EXIT_STATUS_FLAG_HAS_INVALID_CONFIG = 16; + public const EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG = 32; + public const EXIT_STATUS_FLAG_EXCEPTION_IN_APP = 64; + + public function calculate( + bool $isDryRun, + bool $hasChangedFiles, + bool $hasInvalidErrors, + bool $hasExceptionErrors, + bool $hasLintErrorsAfterFixing + ): int { + $exitStatus = 0; + + if ($isDryRun) { + if ($hasChangedFiles) { + $exitStatus |= self::EXIT_STATUS_FLAG_HAS_CHANGED_FILES; + } + + if ($hasInvalidErrors) { + $exitStatus |= self::EXIT_STATUS_FLAG_HAS_INVALID_FILES; + } + } + + if ($hasExceptionErrors || $hasLintErrorsAfterFixing) { + $exitStatus |= self::EXIT_STATUS_FLAG_EXCEPTION_IN_APP; + } + + return $exitStatus; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php new file mode 100644 index 0000000..ae10e39 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerOptionInterface; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand; +use Symfony\Component\Console\Formatter\OutputFormatterStyle; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'help')] +final class HelpCommand extends BaseHelpCommand +{ + public function __construct() + { + parent::__construct('help'); + } + + /** + * Formats the description of an option to include its allowed values. + * + * @param string $description description with a single `%s` placeholder for the allowed values + * @param non-empty-list $allowedValues + */ + public static function getDescriptionWithAllowedValues(string $description, array $allowedValues): string + { + $allowedValues = Utils::naturalLanguageJoinWithBackticks($allowedValues, 'or'); + + return \sprintf($description, 'can be '.$allowedValues); + } + + /** + * Returns the allowed values of the given option that can be converted to a string. + * + * @return null|non-empty-list + */ + public static function getDisplayableAllowedValues(FixerOptionInterface $option): ?array + { + $allowed = $option->getAllowedValues(); + + if (null !== $allowed) { + $allowed = array_filter($allowed, static fn ($value): bool => !$value instanceof \Closure); + + usort($allowed, static function ($valueA, $valueB): int { + if ($valueA instanceof AllowedValueSubset) { + return -1; + } + + if ($valueB instanceof AllowedValueSubset) { + return 1; + } + + return strcasecmp( + Utils::toString($valueA), + Utils::toString($valueB), + ); + }); + + if (0 === \count($allowed)) { + $allowed = null; + } + } + + return $allowed; + } + + protected function initialize(InputInterface $input, OutputInterface $output): void + { + $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue')); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/InitCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/InitCommand.php new file mode 100644 index 0000000..89813d9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/InitCommand.php @@ -0,0 +1,211 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\RuleSet\Sets\AutoRiskySet; +use PhpCsFixer\RuleSet\Sets\AutoSet; +use PhpCsFixer\RuleSet\Sets\PhpCsFixerRiskySet; +use PhpCsFixer\RuleSet\Sets\PhpCsFixerSet; +use PhpCsFixer\RuleSet\Sets\SymfonyRiskySet; +use PhpCsFixer\RuleSet\Sets\SymfonySet; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Filesystem\Exception\IOException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'init', description: 'Create config file.')] +final class InitCommand extends Command +{ + private const FIXER_FILENAME = '.php-cs-fixer.dist.php'; + + public function __construct() + { + parent::__construct('init'); + $this->setDescription('Create config file.'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $stdErr = $output; + + if ($output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln(Application::getAboutWithRuntime(true)); + } + + $io = new SymfonyStyle($input, $stdErr); + + $io->warning('This command is experimental'); + + if (file_exists(self::FIXER_FILENAME)) { + $io->error(\sprintf('Configuration file `%s` already exists.', self::FIXER_FILENAME)); + + return Command::FAILURE; + } + + $io->note([ + 'While we start, we must tell you that we put our diligence to NOT change the meaning of your codebase.', + 'Yet, some of the rules are explicitly _risky_ to apply. A rule is _risky_ if it could change code behaviour, e.g. transforming `==` into `===` or removal of trailing whitespaces within multiline strings.', + 'Such rules are improving your codebase even further, yet you shall always review changes proposed by _risky_ rules carefully.', + ]); + $isRiskyAllowed = 'yes' === $io->choice( + 'Do you want to enable _risky_ rules?', + ['yes', 'no'], + 'no', + ); + + $setsByName = RuleSets::getBuiltInSetDefinitions(); + + $setAuto = new AutoSet(); + $setAutoRisky = new AutoRiskySet(); + $setAutoWithOptionalRiskySetNamesTextual = $isRiskyAllowed ? '`@auto`/`@auto:risky`' : '`@auto`'; + + $io->note("We recommend usage of {$setAutoWithOptionalRiskySetNamesTextual} rulesets. They take insights from your existing `composer.json` to configure project the best:"); + + $generateSetsBehindAutoSet = static function () use ($setAuto, $setAutoRisky, $isRiskyAllowed): array { + $sets = array_merge( + array_keys($setAuto->getRulesCandidates()), + $isRiskyAllowed ? array_keys($setAutoRisky->getRulesCandidates()) : [], + ); + natcasesort($sets); + + return $sets; + }; + $setsBehindAutoSet = $generateSetsBehindAutoSet(); + + $io->listing( + array_map( + static fn (RuleSetDefinitionInterface $item): string => \sprintf( + '`%s` - %s', + $item->getName(), + $item->getDescription(), + ), + array_map( + static fn (string $name): RuleSetDefinitionInterface => $setsByName[$name], // @phpstan-ignore-line offsetAccess.notFound + $setsBehindAutoSet, + ), + ), + ); + + $rules = []; + + $useAutoSet = 'yes' === $io->choice( + "Do you want to use {$setAutoWithOptionalRiskySetNamesTextual} ruleset?", + ['yes', 'no'], + 'yes', + ); + + if ($useAutoSet) { + $rules[] = $setAuto->getName(); + if ($isRiskyAllowed) { + $rules[] = $setAutoRisky->getName(); + } + } + + $generateExtraSets = static function () use ($isRiskyAllowed): array { + $setSymfony = new SymfonySet(); + $setPhpCsFixer = new PhpCsFixerSet(); + + $extraSets = [ + $setSymfony->getName(), + $setPhpCsFixer->getName(), + ]; + + if ($isRiskyAllowed) { + $setSymfonyRisky = new SymfonyRiskySet(); + $setPhpCsFixerRisky = new PhpCsFixerRiskySet(); + + $extraSets[] = $setSymfonyRisky->getName(); + $extraSets[] = $setPhpCsFixerRisky->getName(); + } + + return $extraSets; + }; + + $extraSets = array_merge( + false === $useAutoSet ? $setsBehindAutoSet : [], + $generateExtraSets(), + ); + natcasesort($extraSets); + + $sets = $io->choice( + 'Do you want to use any of other recommended ruleset? (multi-choice)', + array_combine( + $extraSets, + array_map( + static fn (string $item): string => $setsByName[$item]->getDescription(), // @phpstan-ignore-line offsetAccess.notFound + $extraSets, + ), + ) + ['none' => 'none'], + 'none', + true, + ); + + // older Symfony version can return single string instead of array with single string, let's unify + if (!\is_array($sets)) { + $sets = [$sets]; + } + + $rules = array_merge( + $rules, + array_unique(array_filter($sets, static fn ($item) => 'none' !== $item)), + ); + + $readResult = @file_get_contents(__DIR__.'/../../../resources/.php-cs-fixer.dist.php.template'); + if (false === $readResult) { + throw new IOException('Failed to read template file.'); + } + + $content = str_replace( + [ + '/*{{ IS_RISKY_ALLOWED }}*/', + '/*{{ RULES }}*/', + ], + [ + $isRiskyAllowed ? 'true' : 'false', + "[\n".implode( + ",\n", + array_map( + static fn ($item) => " '{$item}' => true", + $rules, + ), + )."\n ]", + ], + $readResult, + ); + + $writeResult = @file_put_contents(self::FIXER_FILENAME, $content); + if (false === $writeResult) { + throw new IOException(\sprintf('Failed to write file "%s".', self::FIXER_FILENAME)); + } + + $io->success(\sprintf('Configuration file created successfully as `%s`.', self::FIXER_FILENAME)); + + return Command::SUCCESS; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php new file mode 100644 index 0000000..10a64de --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Filesystem\Path; + +/** + * @author Markus Staab + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'list-files', description: 'List all files being fixed by the given config.')] +final class ListFilesCommand extends Command +{ + private ConfigInterface $defaultConfig; + + private ToolInfoInterface $toolInfo; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct('list-files'); + $this->setDescription('List all files being fixed by the given config.'); + + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + } + + protected function configure(): void + { + $this->setDefinition( + [ + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.'), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $passedConfig = $input->getOption('config'); + + $cwd = getcwd(); + \assert(false !== $cwd); + + $resolver = new ConfigurationResolver( + $this->defaultConfig, + [ + 'config' => $passedConfig, + ], + $cwd, + $this->toolInfo, + ); + + $finder = $resolver->getFinder(); + + foreach ($finder as $file) { + if ($file->isFile()) { + $relativePath = './'.Path::makeRelative($file->getRealPath(), $cwd); + // unify directory separators across operating system + $relativePath = str_replace('/', \DIRECTORY_SEPARATOR, $relativePath); + + $output->writeln(escapeshellarg($relativePath)); + } + } + + return 0; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListRulesCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListRulesCommand.php new file mode 100644 index 0000000..d70140d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListRulesCommand.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Report\ListRulesReport\ReporterFactory; +use PhpCsFixer\Console\Report\ListRulesReport\ReporterInterface; +use PhpCsFixer\Console\Report\ListRulesReport\ReportSummary; +use PhpCsFixer\Console\Report\ListRulesReport\TextReporter; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'list-rules', description: 'List all available Rules.')] +final class ListRulesCommand extends Command +{ + public function __construct() + { + parent::__construct('list-rules'); + $this->setDescription('List all available Rules.'); + } + + protected function configure(): void + { + $reporterFactory = new ReporterFactory(); + $reporterFactory->registerBuiltInReporters(); + $formats = $reporterFactory->getFormats(); + \assert([] !== $formats); + + $this->setDefinition( + [ + new InputOption('format', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('To output results in other formats (%s).', $formats), (new TextReporter())->getFormat(), $formats), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $reporter = $this->resolveReporterWithFactory( + $input->getOption('format'), + new ReporterFactory(), + ); + + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + + $reportSummary = new ReportSummary( + $fixerFactory->getFixers(), + ); + + $report = $reporter->generate($reportSummary); + + $output->isDecorated() + ? $output->write(OutputFormatter::escape($report)) + : $output->write($report, false, OutputInterface::OUTPUT_RAW); + + return 0; + } + + private function resolveReporterWithFactory(string $format, ReporterFactory $factory): ReporterInterface + { + try { + $factory->registerBuiltInReporters(); + $reporter = $factory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $factory->getFormats(); + sort($formats); + + throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + + return $reporter; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php new file mode 100644 index 0000000..a5eed6f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php @@ -0,0 +1,95 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterFactory; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; +use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; +use PhpCsFixer\Console\Report\ListSetsReport\TextReporter; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Utils; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'list-sets', description: 'List all available RuleSets.')] +final class ListSetsCommand extends Command +{ + public function __construct() + { + parent::__construct('list-sets'); + $this->setDescription('List all available RuleSets.'); + } + + protected function configure(): void + { + $reporterFactory = new ReporterFactory(); + $reporterFactory->registerBuiltInReporters(); + $formats = $reporterFactory->getFormats(); + \assert([] !== $formats); + + $this->setDefinition( + [ + new InputOption('format', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('To output results in other formats (%s).', $formats), (new TextReporter())->getFormat(), $formats), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $reporter = $this->resolveReporterWithFactory( + $input->getOption('format'), + new ReporterFactory(), + ); + + $reportSummary = new ReportSummary( + array_values(RuleSets::getSetDefinitions()), + ); + + $report = $reporter->generate($reportSummary); + + $output->isDecorated() + ? $output->write(OutputFormatter::escape($report)) + : $output->write($report, false, OutputInterface::OUTPUT_RAW); + + return 0; + } + + private function resolveReporterWithFactory(string $format, ReporterFactory $factory): ReporterInterface + { + try { + $factory->registerBuiltInReporters(); + $reporter = $factory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $factory->getFormats(); + sort($formats); + + throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + + return $reporter; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php new file mode 100644 index 0000000..1abd4c2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php @@ -0,0 +1,194 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface; +use PhpCsFixer\PharCheckerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\ToolInfoInterface; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @author Igor Wiedler + * @author Stephane PY + * @author Grégoire Pineau + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'self-update', description: 'Update php-cs-fixer.phar to the latest stable version.')] +final class SelfUpdateCommand extends Command +{ + private NewVersionCheckerInterface $versionChecker; + + private ToolInfoInterface $toolInfo; + + private PharCheckerInterface $pharChecker; + + public function __construct( + NewVersionCheckerInterface $versionChecker, + ToolInfoInterface $toolInfo, + PharCheckerInterface $pharChecker + ) { + parent::__construct('self-update'); + $this->setDescription('Update php-cs-fixer.phar to the latest stable version.'); + + $this->versionChecker = $versionChecker; + $this->toolInfo = $toolInfo; + $this->pharChecker = $pharChecker; + } + + /** + * {@inheritdoc} + * + * Override here to only generate the help copy when used. + */ + public function getHelp(): string + { + return <<<'EOT' + The %command.name% command replace your php-cs-fixer.phar by the + latest version released on: + https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases + + $ php php-cs-fixer.phar %command.name% + + EOT; + } + + protected function configure(): void + { + $this + ->setAliases(['selfupdate']) + ->setDefinition( + [ + new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Force update to next major version if available.'), + ], + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + if ($output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln(Application::getAboutWithRuntime(true)); + } + + if (!$this->toolInfo->isInstalledAsPhar()) { + $output->writeln('Self-update is available only for PHAR version.'); + + return 1; + } + + $currentVersion = $this->getApplication()->getVersion(); + + try { + if (Preg::match('/^v?(?\d+)\./', $currentVersion, $matches)) { + $currentMajor = (int) $matches['major']; + } else { + throw new \Exception('Unable to determine major version.'); + } + + $latestVersion = $this->versionChecker->getLatestVersion(); + $latestVersionOfCurrentMajor = $this->versionChecker->getLatestVersionOfMajor($currentMajor); + } catch (\Exception $exception) { + $output->writeln(\sprintf( + 'Unable to determine newest version: %s', + $exception->getMessage(), + )); + + return 1; + } + + if (1 !== $this->versionChecker->compareVersions($latestVersion, $currentVersion)) { + $output->writeln('PHP CS Fixer is already up-to-date.'); + + return 0; + } + + $remoteTag = $latestVersion; + + if ( + 0 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $latestVersion) + && true !== $input->getOption('force') + ) { + $output->writeln(\sprintf('A new major version of PHP CS Fixer is available (%s)', $latestVersion)); + $output->writeln(\sprintf('Before upgrading please read https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/%s/UPGRADE-v%s.md', $latestVersion, $currentMajor + 1)); + $output->writeln('If you are ready to upgrade run this command with -f'); + $output->writeln('Checking for new minor/patch version...'); + + if (1 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $currentVersion)) { + $output->writeln('No minor update for PHP CS Fixer.'); + + return 0; + } + + $remoteTag = $latestVersionOfCurrentMajor; + } + + \assert(isset($_SERVER['argv'])); + $localFilename = $_SERVER['argv'][0]; + $realPath = realpath($localFilename); + if (false !== $realPath) { + $localFilename = $realPath; + } + + if (!is_writable($localFilename)) { + $output->writeln(\sprintf('No permission to update "%s" file.', $localFilename)); + + return 1; + } + + $tempFilename = \dirname($localFilename).'/'.basename($localFilename, '.phar').'-tmp.phar'; + $remoteFilename = $this->toolInfo->getPharDownloadUri($remoteTag); + + if (false === @copy($remoteFilename, $tempFilename)) { + $output->writeln(\sprintf('Unable to download new version %s from the server.', $remoteTag)); + + return 1; + } + + chmod($tempFilename, 0777 & ~umask()); + + $pharInvalidityReason = $this->pharChecker->checkFileValidity($tempFilename); + if (null !== $pharInvalidityReason) { + unlink($tempFilename); + $output->writeln(\sprintf('The download of %s is corrupt (%s).', $remoteTag, $pharInvalidityReason)); + $output->writeln('Please re-run the "self-update" command to try again.'); + + return 1; + } + + if ('\\' === \DIRECTORY_SEPARATOR) { + // On Windows rename() fails to overwrite the .phar file being executed, so we need to copy() and unlink() instead. + copy($tempFilename, $localFilename); + @unlink($tempFilename); + } else { + rename($tempFilename, $localFilename); + } + + $output->writeln(\sprintf('PHP CS Fixer updated (%s -> %s)', $currentVersion, $remoteTag)); + + return 0; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/WorkerCommand.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/WorkerCommand.php new file mode 100644 index 0000000..225dbe6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Command/WorkerCommand.php @@ -0,0 +1,252 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Command; + +use Clue\React\NDJson\Decoder; +use Clue\React\NDJson\Encoder; +use PhpCsFixer\Cache\NullCacheManager; +use PhpCsFixer\Config; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\Runner\Event\FileProcessed; +use PhpCsFixer\Runner\Parallel\ParallelAction; +use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; +use PhpCsFixer\Runner\Parallel\ParallelisationException; +use PhpCsFixer\Runner\Runner; +use PhpCsFixer\ToolInfoInterface; +use React\EventLoop\StreamSelectLoop; +use React\Socket\ConnectionInterface; +use React\Socket\TcpConnector; +use Symfony\Component\Console\Attribute\AsCommand; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; + +/** + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +#[AsCommand(name: 'worker', description: 'Internal command for running fixers in parallel', hidden: true)] +final class WorkerCommand extends Command +{ + /** @var string Prefix used before JSON-encoded error printed in the worker's process */ + public const ERROR_PREFIX = 'WORKER_ERROR::'; + + private ToolInfoInterface $toolInfo; + private ConfigurationResolver $configurationResolver; + private ErrorsManager $errorsManager; + private EventDispatcherInterface $eventDispatcher; + + /** @var list */ + private array $events; + + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct('worker'); + $this->setDescription('Internal command for running fixers in parallel'); + + $this->setHidden(true); + $this->toolInfo = $toolInfo; + $this->errorsManager = new ErrorsManager(); + $this->eventDispatcher = new EventDispatcher(); + } + + protected function configure(): void + { + $this->setDefinition( + [ + new InputOption('port', null, InputOption::VALUE_REQUIRED, 'Specifies parallelisation server\'s port.'), + new InputOption('identifier', null, InputOption::VALUE_REQUIRED, 'Specifies parallelisation process\' identifier.'), + new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Are risky fixers allowed (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES), + new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'), + new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'), + new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.'), + new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should cache be used (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES), + new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'), + new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'), + new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'), + ], + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $errorOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output; + $identifier = $input->getOption('identifier'); + $port = $input->getOption('port'); + + if (null === $identifier || !is_numeric($port)) { + throw new ParallelisationException('Missing parallelisation options'); + } + + try { + $runner = $this->createRunner($input); + } catch (\Throwable $e) { + throw new ParallelisationException('Unable to create runner: '.$e->getMessage(), 0, $e); + } + + $loop = new StreamSelectLoop(); + $tcpConnector = new TcpConnector($loop); + $tcpConnector + ->connect(\sprintf('127.0.0.1:%d', $port)) + // @codeCoverageIgnoreStart + ->then( + function (ConnectionInterface $connection) use ($loop, $runner, $identifier): void { + $out = new Encoder($connection, \JSON_INVALID_UTF8_IGNORE); + $in = new Decoder($connection, true, 512, \JSON_INVALID_UTF8_IGNORE); + + // [REACT] Initialise connection with the parallelisation operator + $out->write(['action' => ParallelAction::WORKER_HELLO, 'identifier' => $identifier]); + + $handleError = static function (\Throwable $error) use ($out): void { + $out->write([ + 'action' => ParallelAction::WORKER_ERROR_REPORT, + 'class' => \get_class($error), + 'message' => $error->getMessage(), + 'file' => $error->getFile(), + 'line' => $error->getLine(), + 'code' => $error->getCode(), + 'trace' => $error->getTraceAsString(), + ]); + }; + $out->on('error', $handleError); + $in->on('error', $handleError); + + // [REACT] Listen for messages from the parallelisation operator (analysis requests) + $in->on('data', function (array $json) use ($loop, $runner, $out): void { + \assert(isset($json['action'])); + + $action = $json['action']; + + // Parallelisation operator does not have more to do, let's close the connection + if (ParallelAction::RUNNER_THANK_YOU === $action) { + // no payload to assert on + + $loop->stop(); + + return; + } + + if (ParallelAction::RUNNER_REQUEST_ANALYSIS !== $action) { + // At this point we only expect analysis requests, if any other action happen, we need to fix the code. + throw new \LogicException(\sprintf('Unexpected action ParallelAction::%s.', $action)); + } + + \assert(isset( + $json['files'], + )); + + /** @var iterable $files */ + $files = $json['files']; + + foreach ($files as $path) { + // Reset events because we want to collect only those coming from analysed files chunk + $this->events = []; + $runner->setFileIterator(new \ArrayIterator([new \SplFileInfo($path)])); + $analysisResult = $runner->fix(); + + if (1 !== \count($this->events)) { + throw new ParallelisationException('Runner did not report a fixing event or reported too many.'); + } + + if (1 < \count($analysisResult)) { + throw new ParallelisationException('Runner returned more analysis results than expected.'); + } + + $out->write([ + 'action' => ParallelAction::WORKER_RESULT, + 'errors' => $this->errorsManager->forPath($path), + 'file' => $path, + 'fileHash' => $this->events[0]->getFileHash(), + 'fixInfo' => array_pop($analysisResult), + 'memoryUsage' => memory_get_peak_usage(true), + 'status' => $this->events[0]->getStatus(), + ]); + } + + // Request another file chunk (if available, the parallelisation operator will request new "run" action) + $out->write(['action' => ParallelAction::WORKER_GET_FILE_CHUNK]); + }); + }, + static function (\Throwable $error) use ($errorOutput): void { + // @TODO Verify onRejected behaviour → https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/7777#discussion_r1590399285 + $errorOutput->writeln($error->getMessage()); + }, + ) + // @codeCoverageIgnoreEnd + ; + + $loop->run(); + + return Command::SUCCESS; + } + + private function createRunner(InputInterface $input): Runner + { + $passedConfig = $input->getOption('config'); + $passedRules = $input->getOption('rules'); + + if (null !== $passedConfig && ConfigurationResolver::IGNORE_CONFIG_FILE !== $passedConfig && null !== $passedRules) { + throw new \RuntimeException('Passing both `--config` and `--rules` options is not allowed'); + } + + // There's no one single source of truth when it comes to fixing single file, we need to collect statuses from events. + $this->eventDispatcher->addListener(FileProcessed::NAME, function (FileProcessed $event): void { + $this->events[] = $event; + }); + + $this->configurationResolver = new ConfigurationResolver( + new Config(), + [ + 'allow-risky' => $input->getOption('allow-risky'), + 'config' => $passedConfig, + 'dry-run' => $input->getOption('dry-run'), + 'rules' => $passedRules, + 'path' => [], + 'path-mode' => ConfigurationResolver::PATH_MODE_OVERRIDE, // IMPORTANT! WorkerCommand is called with file that already passed filtering, so here we can rely on PATH_MODE_OVERRIDE. + 'using-cache' => $input->getOption('using-cache'), + 'cache-file' => $input->getOption('cache-file'), + 'diff' => $input->getOption('diff'), + 'stop-on-violation' => $input->getOption('stop-on-violation'), + ], + getcwd(), // @phpstan-ignore argument.type + $this->toolInfo, + ); + + return new Runner( + null, // Paths are known when parallelisation server requests new chunk, not now + $this->configurationResolver->getFixers(), + $this->configurationResolver->getDiffer(), + $this->eventDispatcher, + $this->errorsManager, + $this->configurationResolver->getLinter(), + $this->configurationResolver->isDryRun(), + new NullCacheManager(), // IMPORTANT! We pass null cache, as cache is read&write in main process and we do not need to do it again. + $this->configurationResolver->getDirectory(), + $this->configurationResolver->shouldStopOnViolation(), + ParallelConfigFactory::sequential(), // IMPORTANT! Worker must run in sequential mode. + null, + $this->configurationResolver->getConfigFile(), + $this->configurationResolver->getRuleCustomisationPolicy(), + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php new file mode 100644 index 0000000..6a35054 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php @@ -0,0 +1,1064 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use Ergebnis\AgentDetector; +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\Cache\Directory; +use PhpCsFixer\Cache\DirectoryInterface; +use PhpCsFixer\Cache\FileCacheManager; +use PhpCsFixer\Cache\FileHandler; +use PhpCsFixer\Cache\NullCacheManager; +use PhpCsFixer\Cache\Signature; +use PhpCsFixer\Config\NullRuleCustomisationPolicy; +use PhpCsFixer\Config\RuleCustomisationPolicyAwareConfigInterface; +use PhpCsFixer\Config\RuleCustomisationPolicyInterface; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReporterFactory; +use PhpCsFixer\Console\Report\FixReport\ReporterInterface; +use PhpCsFixer\CustomRulesetsAwareConfigInterface; +use PhpCsFixer\Differ\DifferInterface; +use PhpCsFixer\Differ\NullDiffer; +use PhpCsFixer\Differ\UnifiedDiffer; +use PhpCsFixer\Finder; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Future; +use PhpCsFixer\Linter\Linter; +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\ParallelAwareConfigInterface; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSetInterface; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Runner\Parallel\ParallelConfig; +use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\ToolInfoInterface; +use PhpCsFixer\UnsupportedPhpVersionAllowedConfigInterface; +use PhpCsFixer\Utils; +use PhpCsFixer\WhitespacesFixerConfig; +use PhpCsFixer\WordMatcher; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * The resolver that resolves configuration to use by command line options and config. + * + * @internal + * + * @phpstan-type _Options array{ + * allow-risky: null|string, + * cache-file: null|string, + * config: null|string, + * diff: null|string, + * dry-run: null|bool, + * format: null|string, + * path: list, + * path-mode: value-of, + * rules: null|string, + * sequential: null|string, + * show-progress: null|string, + * stop-on-violation: null|bool, + * using-cache: null|string, + * allow-unsupported-php-version: null|bool, + * verbosity: null|string, + * } + * + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ConfigurationResolver +{ + public const IGNORE_CONFIG_FILE = '-'; + + public const PATH_MODE_OVERRIDE = 'override'; + public const PATH_MODE_INTERSECTION = 'intersection'; + public const PATH_MODE_VALUES = [ + self::PATH_MODE_OVERRIDE, + self::PATH_MODE_INTERSECTION, + ]; + + public const BOOL_YES = 'yes'; + public const BOOL_NO = 'no'; + public const BOOL_VALUES = [ + self::BOOL_YES, + self::BOOL_NO, + ]; + + /** + * @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config` + */ + private ?string $deprecatedNestedConfigDir = null; + + private ?bool $allowRisky = null; + + private ?ConfigInterface $config = null; + + private ?string $configFile = null; + + private string $cwd; + + private ConfigInterface $defaultConfig; + + private ?ReporterInterface $reporter = null; + + private ?bool $isStdIn = null; + + private ?bool $isDryRun = null; + + /** + * @var null|list + */ + private ?array $fixers = null; + + private ?bool $configFinderIsOverridden = null; + + private ?bool $configRulesAreOverridden = null; + + private ToolInfoInterface $toolInfo; + + /** + * @var _Options + */ + private array $options = [ + 'allow-risky' => null, + 'cache-file' => null, + 'config' => null, + 'diff' => null, + 'dry-run' => null, + 'format' => null, + 'path' => [], + 'path-mode' => self::PATH_MODE_OVERRIDE, + 'rules' => null, + 'sequential' => null, + 'show-progress' => null, + 'stop-on-violation' => null, + 'using-cache' => null, + 'allow-unsupported-php-version' => null, + 'verbosity' => null, + ]; + + private ?string $cacheFile = null; + + private ?CacheManagerInterface $cacheManager = null; + + private ?DifferInterface $differ = null; + + private ?Directory $directory = null; + + /** + * @var null|iterable<\SplFileInfo> + */ + private ?iterable $finder = null; + + private ?string $format = null; + + private ?Linter $linter = null; + + /** + * @var null|list + */ + private ?array $path = null; + + /** + * @var null|ProgressOutputType::* + */ + private $progress; + + private ?RuleSet $ruleSet = null; + + private ?bool $usingCache = null; + + private ?bool $isUnsupportedPhpVersionAllowed = null; + + private ?RuleCustomisationPolicyInterface $ruleCustomisationPolicy = null; + + private ?FixerFactory $fixerFactory = null; + + /** + * @param array $options + */ + public function __construct( + ConfigInterface $config, + array $options, + string $cwd, + ToolInfoInterface $toolInfo + ) { + $this->defaultConfig = $config; + $this->cwd = $cwd; + $this->toolInfo = $toolInfo; + + foreach ($options as $name => $value) { + $this->setOption($name, $value); + } + } + + public function getCacheFile(): ?string + { + if (!$this->getUsingCache()) { + return null; + } + + if (null === $this->cacheFile) { + if (null === $this->options['cache-file']) { + $this->cacheFile = $this->getConfig()->getCacheFile(); + } else { + $this->cacheFile = $this->options['cache-file']; + } + } + + return $this->cacheFile; + } + + public function getCacheManager(): CacheManagerInterface + { + if (null === $this->cacheManager) { + $cacheFile = $this->getCacheFile(); + + if (null === $cacheFile) { + $this->cacheManager = new NullCacheManager(); + } else { + $this->cacheManager = new FileCacheManager( + new FileHandler($cacheFile), + new Signature( + \PHP_VERSION, + $this->toolInfo->getVersion(), + $this->getConfig()->getIndent(), + $this->getConfig()->getLineEnding(), + $this->getRules(), + $this->getRuleCustomisationPolicy()->getPolicyVersionForCache(), + ), + $this->isDryRun(), + $this->getDirectory(), + ); + } + } + + return $this->cacheManager; + } + + public function getConfig(): ConfigInterface + { + if (null === $this->config) { + foreach ($this->computeConfigFiles() as $configFile) { + if (!file_exists($configFile)) { + continue; + } + + $configFileBasename = basename($configFile); + + /** @TODO v4 drop handling (triggering error) for v2 config names */ + $deprecatedConfigs = [ + '.php_cs' => '.php-cs-fixer.php', + '.php_cs.dist' => '.php-cs-fixer.dist.php', + ]; + + if (isset($deprecatedConfigs[$configFileBasename])) { + throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`."); + } + + if (null !== $this->deprecatedNestedConfigDir && str_starts_with($configFile, $this->deprecatedNestedConfigDir)) { + // @TODO v4: when removing, remove also TODO with `MARKER-multi-paths-vs-only-cwd-config` + Future::triggerDeprecation( + new InvalidConfigurationException("Configuration file `{$configFile}` is picked as file inside passed `path` CLI argument. This will be ignored in the future and only config file in `cwd` will be picked. Please use `config` CLI option instead if you want to keep current behaviour."), + ); + } + + $this->config = self::separatedContextLessInclude($configFile); + $this->configFile = $configFile; + + break; + } + + if (null === $this->config) { + $this->config = $this->defaultConfig; + } + + if ($this->config instanceof CustomRulesetsAwareConfigInterface) { + foreach ($this->config->getCustomRuleSets() as $ruleSet) { + RuleSets::registerCustomRuleSet($ruleSet); + } + } + } + + return $this->config; + } + + public function getParallelConfig(): ParallelConfig + { + $config = $this->getConfig(); + + return true !== $this->options['sequential'] && $config instanceof ParallelAwareConfigInterface + ? $config->getParallelConfig() + : ParallelConfigFactory::sequential(); + } + + public function getConfigFile(): ?string + { + if (null === $this->configFile) { + $this->getConfig(); + } + + return $this->configFile; + } + + public function getDiffer(): DifferInterface + { + if (null === $this->differ) { + $this->differ = (true === $this->options['diff']) ? new UnifiedDiffer() : new NullDiffer(); + } + + return $this->differ; + } + + public function getDirectory(): DirectoryInterface + { + if (null === $this->directory) { + $cwd = realpath($this->cwd); + + $this->directory = new Directory(false !== $cwd ? $cwd : $this->cwd); + } + + return $this->directory; + } + + /** + * @return list + */ + public function getFixers(): array + { + if (null === $this->fixers) { + $this->fixers = $this->createFixerFactory() + ->useRuleSet($this->getRuleSet()) + ->setWhitespacesConfig(new WhitespacesFixerConfig($this->config->getIndent(), $this->config->getLineEnding())) + ->getFixers() + ; + + if (false === $this->getRiskyAllowed()) { + $riskyFixers = array_map( + static fn (FixerInterface $fixer): string => $fixer->getName(), + array_values(array_filter( + $this->fixers, + static fn (FixerInterface $fixer): bool => $fixer->isRisky(), + )), + ); + + if (\count($riskyFixers) > 0) { + throw new InvalidConfigurationException(\sprintf('The rules contain risky fixers (%s), but they are not allowed to run. Perhaps you forget to use --allow-risky=yes option?', Utils::naturalLanguageJoin($riskyFixers))); + } + } + } + + return $this->fixers; + } + + public function getLinter(): LinterInterface + { + if (null === $this->linter) { + $this->linter = new Linter(); + } + + return $this->linter; + } + + /** + * Returns path. + * + * @return list + */ + public function getPath(): array + { + if (null === $this->path) { + $filesystem = new Filesystem(); + $cwd = $this->cwd; + + if (1 === \count($this->options['path']) && '-' === $this->options['path'][0]) { + $this->path = $this->options['path']; + } else { + $this->path = array_map( + static function (string $rawPath) use ($cwd, $filesystem): string { + $path = trim($rawPath); + + if ('' === $path) { + throw new InvalidConfigurationException("Invalid path: \"{$rawPath}\"."); + } + + $absolutePath = $filesystem->isAbsolutePath($path) + ? $path + : $cwd.\DIRECTORY_SEPARATOR.$path; + + if (!file_exists($absolutePath)) { + throw new InvalidConfigurationException(\sprintf( + 'The path "%s" is not readable.', + $path, + )); + } + + return $absolutePath; + }, + $this->options['path'], + ); + } + } + + return $this->path; + } + + /** + * @return ProgressOutputType::* + * + * @throws InvalidConfigurationException + */ + public function getProgressType(): string + { + if (null === $this->progress) { + if ('txt' === $this->resolveFormat()) { + $progressType = $this->options['show-progress']; + + if (null === $progressType) { + $progressType = $this->getConfig()->getHideProgress() + ? ProgressOutputType::NONE + : ProgressOutputType::BAR; + } elseif (!\in_array($progressType, ProgressOutputType::all(), true)) { + throw new InvalidConfigurationException(\sprintf( + 'The progress type "%s" is not defined, supported are %s.', + $progressType, + Utils::naturalLanguageJoin(ProgressOutputType::all()), + )); + } + + $this->progress = $progressType; + } else { + $this->progress = ProgressOutputType::NONE; + } + } + + return $this->progress; + } + + public function getReporter(): ReporterInterface + { + if (null === $this->reporter) { + $reporterFactory = new ReporterFactory(); + $reporterFactory->registerBuiltInReporters(); + + $format = $this->resolveFormat(); + + try { + $this->reporter = $reporterFactory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $reporterFactory->getFormats(); + sort($formats); + + throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + } + + return $this->reporter; + } + + public function getRiskyAllowed(): bool + { + if (null === $this->allowRisky) { + if (null === $this->options['allow-risky']) { + $this->allowRisky = $this->getConfig()->getRiskyAllowed(); + } else { + $this->allowRisky = $this->resolveOptionBooleanValue('allow-risky'); + } + } + + return $this->allowRisky; + } + + /** + * Returns rules. + * + * @return array|bool> + */ + public function getRules(): array + { + return $this->getRuleSet()->getRules(); + } + + public function getUsingCache(): bool + { + if (null === $this->usingCache) { + if (null === $this->options['using-cache']) { + $this->usingCache = $this->getConfig()->getUsingCache(); + } else { + $this->usingCache = $this->resolveOptionBooleanValue('using-cache'); + } + } + + $this->usingCache = $this->usingCache && $this->isCachingAllowedForRuntime(); + + return $this->usingCache; + } + + public function getUnsupportedPhpVersionAllowed(): bool + { + if (null === $this->isUnsupportedPhpVersionAllowed) { + if (null === $this->options['allow-unsupported-php-version']) { + $config = $this->getConfig(); + $this->isUnsupportedPhpVersionAllowed = $config instanceof UnsupportedPhpVersionAllowedConfigInterface + ? $config->getUnsupportedPhpVersionAllowed() + : false; + } else { + $this->isUnsupportedPhpVersionAllowed = $this->resolveOptionBooleanValue('allow-unsupported-php-version'); + } + } + + return $this->isUnsupportedPhpVersionAllowed; + } + + public function getRuleCustomisationPolicy(): RuleCustomisationPolicyInterface + { + if (null === $this->ruleCustomisationPolicy) { + $config = $this->getConfig(); + if ($config instanceof RuleCustomisationPolicyAwareConfigInterface) { + $this->ruleCustomisationPolicy = $config->getRuleCustomisationPolicy(); + } + $this->ruleCustomisationPolicy ??= new NullRuleCustomisationPolicy(); + } + + return $this->ruleCustomisationPolicy; + } + + /** + * @return iterable<\SplFileInfo> + */ + public function getFinder(): iterable + { + if (null === $this->finder) { + $this->finder = $this->resolveFinder(); + } + + return $this->finder; + } + + /** + * Returns dry-run flag. + */ + public function isDryRun(): bool + { + if (null === $this->isDryRun) { + if ($this->isStdIn()) { + // Can't write to STDIN + $this->isDryRun = true; + } else { + $this->isDryRun = $this->options['dry-run']; + } + } + + return $this->isDryRun; + } + + public function shouldStopOnViolation(): bool + { + return $this->options['stop-on-violation']; + } + + public function configFinderIsOverridden(): bool + { + if (null === $this->configFinderIsOverridden) { + $this->resolveFinder(); + } + + return $this->configFinderIsOverridden; + } + + public function configRulesAreOverridden(): bool + { + if (null === $this->configRulesAreOverridden) { + $this->parseRules(); + } + + return $this->configRulesAreOverridden; + } + + /** + * Compute file candidates for config file. + * + * @TODO v4: don't offer configs from passed `path` CLI argument + * + * @return list + */ + private function computeConfigFiles(): array + { + $configFile = $this->options['config']; + + if (self::IGNORE_CONFIG_FILE === $configFile) { + return []; + } + + if (null !== $configFile) { + if (false === file_exists($configFile) || false === is_readable($configFile)) { + throw new InvalidConfigurationException(\sprintf('Cannot read config file "%s".', $configFile)); + } + + return [$configFile]; + } + + $path = $this->getPath(); + + if ($this->isStdIn() || 0 === \count($path)) { + $configDir = $this->cwd; + } elseif (1 < \count($path)) { + // @TODO v4: this is no longer needed due to `MARKER-multi-paths-vs-only-cwd-config` + throw new InvalidConfigurationException('For multiple paths config parameter is required.'); + } elseif (!is_file($path[0])) { + $configDir = $path[0]; + } else { + $dirName = pathinfo($path[0], \PATHINFO_DIRNAME); + $configDir = is_dir($dirName) ? $dirName : $path[0]; + } + + $candidates = [ + $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php', + $configDir.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php', + + // @TODO v4 drop handling (triggering error) for v2 config names + $configDir.\DIRECTORY_SEPARATOR.'.php_cs', // old v2 config, present here only to throw nice error message later + $configDir.\DIRECTORY_SEPARATOR.'.php_cs.dist', // old v2 config, present here only to throw nice error message later + ]; + + if ($configDir !== $this->cwd) { + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.php'; + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php-cs-fixer.dist.php'; + + // @TODO v4 drop handling (triggering error) for v2 config names + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs'; // old v2 config, present here only to throw nice error message later + $candidates[] = $this->cwd.\DIRECTORY_SEPARATOR.'.php_cs.dist'; // old v2 config, present here only to throw nice error message later + + $this->deprecatedNestedConfigDir = $configDir; + } + + return $candidates; + } + + private function createFixerFactory(): FixerFactory + { + if (null === $this->fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers()); + + $this->fixerFactory = $fixerFactory; + } + + return $this->fixerFactory; + } + + private function resolveFormat(): string + { + if (null === $this->format) { + $formatCandidate = $this->options['format'] ?? $this->getConfig()->getFormat(); + $parts = explode(',', $formatCandidate); + + if (\count($parts) > 2) { + throw new InvalidConfigurationException(\sprintf('The format "%s" is invalid.', $formatCandidate)); + } + + $this->format = $parts[0]; + + if ('@auto' === $this->format) { + if (filter_var(getenv('GITLAB_CI'), \FILTER_VALIDATE_BOOL)) { + $this->format = 'gitlab'; + + return $this->format; + } + + $agentDetector = new AgentDetector\Detector(); + + if ($agentDetector->isAgentPresent(array_fill_keys(array_keys(getenv()), ''))) { + $this->format = 'json'; + + return $this->format; + } + + $this->format = $parts[1] ?? 'txt'; + } + } + + return $this->format; + } + + private function getRuleSet(): RuleSetInterface + { + if (null === $this->ruleSet) { + $rules = $this->parseRules(); + $this->validateRules($rules); + + $this->ruleSet = new RuleSet($rules); + } + + return $this->ruleSet; + } + + private function isStdIn(): bool + { + if (null === $this->isStdIn) { + $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0]; + } + + return $this->isStdIn; + } + + /** + * @return array + */ + private function parseRules(): array + { + $this->configRulesAreOverridden = null !== $this->options['rules']; + + if (null === $this->options['rules']) { + $this->configRulesAreOverridden = false; + + return $this->getConfig()->getRules(); + } + + $rules = trim($this->options['rules']); + if ('' === $rules) { + throw new InvalidConfigurationException('Empty rules value is not allowed.'); + } + + if (str_starts_with($rules, '{')) { + try { + return json_decode($rules, true, 512, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new InvalidConfigurationException(\sprintf('Invalid JSON rules input: "%s".', $e->getMessage())); + } + } + + $rules = []; + + foreach (explode(',', $this->options['rules']) as $rule) { + $rule = trim($rule); + + if ('' === $rule) { + throw new InvalidConfigurationException('Empty rule name is not allowed.'); + } + + if (str_starts_with($rule, '-')) { + $rules[substr($rule, 1)] = false; + } else { + $rules[$rule] = true; + } + } + + $this->configRulesAreOverridden = true; + + return $rules; + } + + /** + * @param array $rules + * + * @throws InvalidConfigurationException + */ + private function validateRules(array $rules): void + { + /** + * Create a ruleset that contains all configured rules, even when they originally have been disabled. + * + * @see RuleSet::resolveSet() + */ + $ruleSet = []; + + foreach ($rules as $key => $value) { + if (\is_int($key)) { + throw new InvalidConfigurationException(\sprintf('Missing value for "%s" rule/set.', $value)); + } + + $ruleSet[$key] = true; + } + + $ruleSet = new RuleSet($ruleSet); + + $configuredFixers = array_keys($ruleSet->getRules()); + + $fixers = $this->createFixerFactory()->getFixers(); + + $availableFixers = array_map(static fn (FixerInterface $fixer): string => $fixer->getName(), $fixers); + + $unknownFixers = array_diff($configuredFixers, $availableFixers); + + if (\count($unknownFixers) > 0) { + /** + * @TODO v4: `renamedRulesFromV2ToV3` no longer needed + * @TODO v3.99: decide how to handle v3 to v4 (where legacy rules are already removed) + */ + $renamedRulesFromV2ToV3 = [ + 'blank_line_before_return' => [ + 'new_name' => 'blank_line_before_statement', + 'config' => ['statements' => ['return']], + ], + 'final_static_access' => [ + 'new_name' => 'self_static_accessor', + ], + 'hash_to_slash_comment' => [ + 'new_name' => 'single_line_comment_style', + 'config' => ['comment_types' => ['hash']], + ], + 'lowercase_constants' => [ + 'new_name' => 'constant_case', + 'config' => ['case' => 'lower'], + ], + 'no_extra_consecutive_blank_lines' => [ + 'new_name' => 'no_extra_blank_lines', + ], + 'no_multiline_whitespace_before_semicolons' => [ + 'new_name' => 'multiline_whitespace_before_semicolons', + ], + 'no_short_echo_tag' => [ + 'new_name' => 'echo_tag_syntax', + 'config' => ['format' => 'long'], + ], + 'php_unit_ordered_covers' => [ + 'new_name' => 'phpdoc_order_by_value', + 'config' => ['annotations' => ['covers']], + ], + 'phpdoc_inline_tag' => [ + 'new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type', + ], + 'pre_increment' => [ + 'new_name' => 'increment_style', + 'config' => ['style' => 'pre'], + ], + 'psr0' => [ + 'new_name' => 'psr_autoloading', + 'config' => ['dir' => 'x'], + ], + 'psr4' => [ + 'new_name' => 'psr_autoloading', + ], + 'silenced_deprecation_error' => [ + 'new_name' => 'error_suppression', + ], + 'trailing_comma_in_multiline_array' => [ + 'new_name' => 'trailing_comma_in_multiline', + 'config' => ['elements' => ['arrays']], + ], + ]; + + $message = 'The rules contain unknown fixers: '; + $hasOldRule = false; + + foreach ($unknownFixers as $unknownFixer) { + if (isset($renamedRulesFromV2ToV3[$unknownFixer])) { // Check if present as old renamed rule + $hasOldRule = true; + $message .= \sprintf( + '"%s" is renamed (did you mean "%s"?%s), ', + $unknownFixer, + $renamedRulesFromV2ToV3[$unknownFixer]['new_name'], + isset($renamedRulesFromV2ToV3[$unknownFixer]['config']) ? ' (note: use configuration "'.Utils::toString($renamedRulesFromV2ToV3[$unknownFixer]['config']).'")' : '', + ); + } else { // Go to normal matcher if it is not a renamed rule + $matcher = new WordMatcher($availableFixers); + $alternative = $matcher->match($unknownFixer); + $message .= \sprintf( + '"%s"%s, ', + $unknownFixer, + null === $alternative ? '' : ' (did you mean "'.$alternative.'"?)', + ); + } + } + + $message = substr($message, 0, -2).'.'; + + if ($hasOldRule) { + $message .= "\nFor more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless."; + } + + throw new InvalidConfigurationException($message); + } + + foreach ($fixers as $fixer) { + $fixerName = $fixer->getName(); + if (isset($rules[$fixerName]) && $fixer instanceof DeprecatedFixerInterface) { + $successors = $fixer->getSuccessorsNames(); + $messageEnd = [] === $successors + ? \sprintf(' and will be removed in version %d.0.', Application::getMajorVersion() + 1) + : \sprintf('. Use %s instead.', str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors))); + + Future::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}")); + } + } + } + + /** + * Apply path on config instance. + * + * @return iterable<\SplFileInfo> + */ + private function resolveFinder(): iterable + { + $this->configFinderIsOverridden = false; + + if ($this->isStdIn()) { + return new \ArrayIterator([new StdinFileInfo()]); + } + + if (!\in_array( + $this->options['path-mode'], + self::PATH_MODE_VALUES, + true, + )) { + throw new InvalidConfigurationException(\sprintf( + 'The path-mode "%s" is not defined, supported are %s.', + $this->options['path-mode'], + Utils::naturalLanguageJoin(self::PATH_MODE_VALUES), + )); + } + + $isIntersectionPathMode = self::PATH_MODE_INTERSECTION === $this->options['path-mode']; + + $paths = array_map( + static fn (string $path): string => realpath($path), // @phpstan-ignore return.type + $this->getPath(), + ); + + if (0 === \count($paths)) { + if ($isIntersectionPathMode) { + return new \ArrayIterator([]); + } + + return $this->getConfig()->getFinder(); + } + + $pathsByType = [ + 'file' => [], + 'dir' => [], + ]; + + foreach ($paths as $path) { + if (is_file($path)) { + $pathsByType['file'][] = $path; + } else { + $pathsByType['dir'][] = $path.\DIRECTORY_SEPARATOR; + } + } + + $nestedFinder = null; + $currentFinder = $this->getConfig()->getFinder(); + + try { + $nestedFinder = $currentFinder instanceof \IteratorAggregate + ? $currentFinder->getIterator() + : ( + $currentFinder instanceof \Traversable + ? $currentFinder + : new \ArrayIterator($currentFinder) + ); + } catch (\Exception $e) { + } + + if ($isIntersectionPathMode) { + if (null === $nestedFinder) { + throw new InvalidConfigurationException( + 'Cannot create intersection with not-fully defined Finder in configuration file.', + ); + } + + return new \CallbackFilterIterator( + new \IteratorIterator($nestedFinder), + static function (\SplFileInfo $current) use ($pathsByType): bool { + $currentRealPath = $current->getRealPath(); + + if (\in_array($currentRealPath, $pathsByType['file'], true)) { + return true; + } + + foreach ($pathsByType['dir'] as $path) { + if (str_starts_with($currentRealPath, $path)) { + return true; + } + } + + return false; + }, + ); + } + + if (null !== $this->getConfigFile() && null !== $nestedFinder) { + $this->configFinderIsOverridden = true; + } + + if ($currentFinder instanceof SymfonyFinder && null === $nestedFinder) { + // finder from configuration Symfony finder and it is not fully defined, we may fulfill it + return $currentFinder->in($pathsByType['dir'])->append($pathsByType['file']); + } + + return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']); + } + + /** + * Set option that will be resolved. + * + * @param mixed $value + */ + private function setOption(string $name, $value): void + { + if (!\array_key_exists($name, $this->options)) { + throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name)); + } + + $this->options[$name] = $value; + } + + /** + * @param key-of<_Options> $optionName + */ + private function resolveOptionBooleanValue(string $optionName): bool + { + $value = $this->options[$optionName]; + + if (self::BOOL_YES === $value) { + return true; + } + + if (self::BOOL_NO === $value) { + return false; + } + + throw new InvalidConfigurationException(\sprintf('Expected "%s" or "%s" for option "%s", got "%s".', self::BOOL_YES, self::BOOL_NO, $optionName, \is_object($value) ? \get_class($value) : (\is_scalar($value) ? $value : \gettype($value)))); + } + + private static function separatedContextLessInclude(string $path): ConfigInterface + { + $config = include $path; + + // verify that the config has an instance of Config + if (!$config instanceof ConfigInterface) { + throw new InvalidConfigurationException(\sprintf('The config file: "%s" does not return a "%s" instance. Got: "%s".', $path, ConfigInterface::class, get_debug_type($config))); + } + + return $config; + } + + private function isCachingAllowedForRuntime(): bool + { + return $this->toolInfo->isInstalledAsPhar() + || $this->toolInfo->isInstalledByComposer() + || $this->toolInfo->isRunInsideDocker() + || filter_var(getenv('PHP_CS_FIXER_ENFORCE_CACHE'), \FILTER_VALIDATE_BOOL); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php new file mode 100644 index 0000000..5d80eb9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output; + +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Error\Error; +use PhpCsFixer\Linter\LintingException; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ErrorOutput +{ + private OutputInterface $output; + + private bool $isDecorated; + + public function __construct(OutputInterface $output) + { + $this->output = $output; + $this->isDecorated = $output->isDecorated(); + } + + /** + * @param list $errors + */ + public function listErrors(string $process, array $errors): void + { + $this->output->writeln(['', \sprintf( + 'Files that were not fixed due to errors reported during %s:', + $process, + )]); + + $showDetails = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE; + $showTrace = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG; + foreach ($errors as $i => $error) { + $this->output->writeln(\sprintf('%4d) %s', $i + 1, $error->getFilePath())); + $e = $error->getSource(); + if (!$showDetails || null === $e) { + continue; + } + + $class = \sprintf('[%s]', \get_class($e)); + $message = $e->getMessage(); + $code = $e->getCode(); + if (0 !== $code) { + $message .= " ({$code})"; + } + + $length = max(\strlen($class), \strlen($message)); + $lines = [ + '', + $class, + $message, + '', + ]; + + $this->output->writeln(''); + + foreach ($lines as $line) { + if (\strlen($line) < $length) { + $line .= str_repeat(' ', $length - \strlen($line)); + } + + $this->output->writeln(\sprintf(' %s ', $this->prepareOutput($line))); + } + + if ($showTrace && !$e instanceof LintingException) { // stack trace of lint exception is of no interest + $this->output->writeln(''); + $stackTrace = $e->getTrace(); + foreach ($stackTrace as $trace) { + if (isset($trace['class']) && Command::class === $trace['class'] && 'run' === $trace['function']) { + $this->output->writeln(' [ ... ]'); + + break; + } + + $this->outputTrace($trace); + } + } + + if (Error::TYPE_LINT === $error->getType() && 0 < \count($error->getAppliedFixers())) { + $this->output->writeln(''); + $this->output->writeln(\sprintf(' Applied fixers: %s', implode(', ', $error->getAppliedFixers()))); + + $diff = $error->getDiff(); + if ('' !== $diff) { + $diffFormatter = new DiffConsoleFormatter( + $this->isDecorated, + \sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + \PHP_EOL, + \PHP_EOL, + ), + ); + + $this->output->writeln($diffFormatter->format($diff)); + } + } + } + } + + /** + * @param array{ + * function?: string, + * line?: int, + * file?: string, + * class?: class-string, + * type?: '->'|'::', + * args?: list, + * object?: object, + * } $trace + */ + private function outputTrace(array $trace): void + { + if (isset($trace['class'], $trace['type'], $trace['function'])) { + $this->output->writeln(\sprintf( + ' %s%s%s()', + $this->prepareOutput($trace['class']), + $this->prepareOutput($trace['type']), + $this->prepareOutput($trace['function']), + )); + } elseif (isset($trace['function'])) { + $this->output->writeln(\sprintf(' %s()', $this->prepareOutput($trace['function']))); + } + + if (isset($trace['file'])) { + $this->output->writeln( + \sprintf(' in %s', $this->prepareOutput($trace['file'])) + .(isset($trace['line']) ? \sprintf(' at line %d', $trace['line']) : ' at unknown line'), + ); + } + } + + private function prepareOutput(string $string): string + { + return $this->isDecorated + ? OutputFormatter::escape($string) + : $string; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php new file mode 100644 index 0000000..75ff3aa --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output; + +use Symfony\Component\Console\Output\OutputInterface; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OutputContext +{ + private ?OutputInterface $output; + private int $terminalWidth; + private int $filesCount; + + public function __construct( + ?OutputInterface $output, + int $terminalWidth, + int $filesCount + ) { + $this->output = $output; + $this->terminalWidth = $terminalWidth; + $this->filesCount = $filesCount; + } + + public function getOutput(): ?OutputInterface + { + return $this->output; + } + + public function getTerminalWidth(): int + { + return $this->terminalWidth; + } + + public function getFilesCount(): int + { + return $this->filesCount; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php new file mode 100644 index 0000000..25997f3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\Runner\Event\FileProcessed; +use Symfony\Component\Console\Output\OutputInterface; + +/** + * Output writer to show the progress of a FixCommand using dots and meaningful letters. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DotsOutput implements ProgressOutputInterface +{ + /** + * File statuses map. + * + * @var array + */ + private const EVENT_STATUS_MAP = [ + FileProcessed::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'], + FileProcessed::STATUS_FIXED => ['symbol' => 'F', 'format' => '%s', 'description' => 'fixed'], + FileProcessed::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '%s', 'description' => 'skipped (cached or empty file)'], + FileProcessed::STATUS_NON_MONOLITHIC => ['symbol' => 'M', 'format' => '%s', 'description' => 'skipped (non-monolithic)'], + FileProcessed::STATUS_INVALID => ['symbol' => 'I', 'format' => '%s', 'description' => 'invalid file syntax (file ignored)'], + FileProcessed::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], + FileProcessed::STATUS_LINT => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], + ]; + + /** @readonly */ + private OutputContext $context; + + private int $processedFiles = 0; + + private int $symbolsPerLine; + + public function __construct(OutputContext $context) + { + $this->context = $context; + + // max number of characters per line + // - total length x 2 (e.g. " 1 / 123" => 6 digits and padding spaces) + // - 11 (extra spaces, parentheses and percentage characters, e.g. " x / x (100%)") + $this->symbolsPerLine = max(1, $context->getTerminalWidth() - \strlen((string) $context->getFilesCount()) * 2 - 11); + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __serialize(): array + { + throw new \BadMethodCallException('Cannot serialize '.self::class); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @param array $data + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __unserialize(array $data): void + { + throw new \BadMethodCallException('Cannot unserialize '.self::class); + } + + public function onFixerFileProcessed(FileProcessed $event): void + { + $status = self::EVENT_STATUS_MAP[$event->getStatus()]; + $this->getOutput()->write($this->getOutput()->isDecorated() ? \sprintf($status['format'], $status['symbol']) : $status['symbol']); + + ++$this->processedFiles; + + $symbolsOnCurrentLine = $this->processedFiles % $this->symbolsPerLine; + $isLast = $this->processedFiles === $this->context->getFilesCount(); + + if (0 === $symbolsOnCurrentLine || $isLast) { + $this->getOutput()->write(\sprintf( + '%s %'.\strlen((string) $this->context->getFilesCount()).'d / %d (%3d%%)', + $isLast && 0 !== $symbolsOnCurrentLine ? str_repeat(' ', $this->symbolsPerLine - $symbolsOnCurrentLine) : '', + $this->processedFiles, + $this->context->getFilesCount(), + round($this->processedFiles / $this->context->getFilesCount() * 100), + )); + + if (!$isLast) { + $this->getOutput()->writeln(''); + } + } + } + + public function printLegend(): void + { + $symbols = []; + + foreach (self::EVENT_STATUS_MAP as $status) { + $symbol = $status['symbol']; + if (isset($symbols[$symbol])) { + continue; + } + + $symbols[$symbol] = \sprintf('%s-%s', $this->getOutput()->isDecorated() ? \sprintf($status['format'], $symbol) : $symbol, $status['description']); + } + + $this->getOutput()->write(\sprintf("\nLegend: %s\n", implode(', ', $symbols))); + } + + private function getOutput(): OutputInterface + { + return $this->context->getOutput(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php new file mode 100644 index 0000000..0b4a037 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Runner\Event\FileProcessed; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullOutput implements ProgressOutputInterface +{ + public function printLegend(): void {} + + public function onFixerFileProcessed(FileProcessed $event): void {} +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/PercentageBarOutput.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/PercentageBarOutput.php new file mode 100644 index 0000000..537a949 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/PercentageBarOutput.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\Runner\Event\FileProcessed; +use Symfony\Component\Console\Helper\ProgressBar; + +/** + * Output writer to show the progress of a FixCommand using progress bar (percentage). + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PercentageBarOutput implements ProgressOutputInterface +{ + /** @readonly */ + private OutputContext $context; + + private ProgressBar $progressBar; + + public function __construct(OutputContext $context) + { + $this->context = $context; + + $this->progressBar = new ProgressBar($context->getOutput(), $this->context->getFilesCount()); + $this->progressBar->setBarCharacter('▓'); // dark shade character \u2593 + $this->progressBar->setEmptyBarCharacter('░'); // light shade character \u2591 + $this->progressBar->setProgressCharacter(''); + $this->progressBar->setFormat('normal'); + + $this->progressBar->start(); + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __serialize(): array + { + throw new \BadMethodCallException('Cannot serialize '.self::class); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @param array $data + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __unserialize(array $data): void + { + throw new \BadMethodCallException('Cannot unserialize '.self::class); + } + + public function onFixerFileProcessed(FileProcessed $event): void + { + $this->progressBar->advance(1); + + if ($this->progressBar->getProgress() === $this->progressBar->getMaxSteps()) { + $this->context->getOutput()->write("\n\n"); + } + } + + public function printLegend(): void {} +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php new file mode 100644 index 0000000..3426aa4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProgressOutputFactory +{ + /** + * @var array> + */ + private const OUTPUT_TYPE_MAP = [ + ProgressOutputType::NONE => NullOutput::class, + ProgressOutputType::DOTS => DotsOutput::class, + ProgressOutputType::BAR => PercentageBarOutput::class, + ]; + + /** + * @param ProgressOutputType::* $outputType + */ + public function create(string $outputType, OutputContext $context): ProgressOutputInterface + { + if (null === $context->getOutput()) { + $outputType = ProgressOutputType::NONE; + } + + if (!$this->isBuiltInType($outputType)) { + throw new \InvalidArgumentException( + \sprintf( + 'Something went wrong, "%s" output type is not supported', + $outputType, + ), + ); + } + + $outputClass = self::OUTPUT_TYPE_MAP[$outputType]; + + // @phpstan-ignore-next-line new.noConstructor + return new $outputClass($context); + } + + private function isBuiltInType(string $outputType): bool + { + return \in_array($outputType, ProgressOutputType::all(), true); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php new file mode 100644 index 0000000..feaabec --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Runner\Event\FileProcessed; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ProgressOutputInterface +{ + public function printLegend(): void; + + public function onFixerFileProcessed(FileProcessed $event): void; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php new file mode 100644 index 0000000..6cdc4b1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Output\Progress; + +/** + * @TODO PHP 8.1 switch this and similar classes to ENUM + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProgressOutputType +{ + public const NONE = 'none'; + public const DOTS = 'dots'; + public const BAR = 'bar'; + + /** + * @return non-empty-list + */ + public static function all(): array + { + return [ + self::BAR, + self::DOTS, + self::NONE, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php new file mode 100644 index 0000000..d1d938c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Console\Application; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Kévin Gomez + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CheckstyleReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'checkstyle'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + + $checkstyles = $dom->appendChild($dom->createElement('checkstyle')); + \assert($checkstyles instanceof \DOMElement); + + $checkstyles->setAttribute('version', Application::getAbout()); + + foreach ($reportSummary->getChanged() as $filePath => $fixResult) { + $file = $checkstyles->appendChild($dom->createElement('file')); + \assert($file instanceof \DOMElement); + + $file->setAttribute('name', $filePath); + + foreach ($fixResult['appliedFixers'] as $appliedFixer) { + $error = $this->createError($dom, $appliedFixer); + $file->appendChild($error); + } + } + + $dom->formatOutput = true; + + $result = $dom->saveXML(); + if (false === $result) { + throw new \RuntimeException('Failed to generate XML output'); + } + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($result) : $result; + } + + private function createError(\DOMDocument $dom, string $appliedFixer): \DOMElement + { + $error = $dom->createElement('error'); + $error->setAttribute('severity', 'warning'); + $error->setAttribute('source', 'PHP-CS-Fixer.'.$appliedFixer); + $error->setAttribute('message', 'Found violation(s) of type: '.$appliedFixer); + + return $error; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php new file mode 100644 index 0000000..0415ddd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php @@ -0,0 +1,174 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\Documentation\DocumentationLocator; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerFactory; +use SebastianBergmann\Diff\Chunk; +use SebastianBergmann\Diff\Diff; +use SebastianBergmann\Diff\Line; +use SebastianBergmann\Diff\Parser; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * Generates a report according to gitlabs subset of codeclimate json files. + * + * @author Hans-Christian Otto + * @author Dariusz Rumiński + * + * @see https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#data-types + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GitlabReporter implements ReporterInterface +{ + private Parser $diffParser; + private DocumentationLocator $documentationLocator; + private FixerFactory $fixerFactory; + + /** + * @var array + */ + private array $fixers; + + public function __construct() + { + $this->diffParser = new Parser(); + $this->documentationLocator = new DocumentationLocator(); + + $this->fixerFactory = new FixerFactory(); + $this->fixerFactory->registerBuiltInFixers(); + + $this->fixers = $this->createFixers(); + } + + public function getFormat(): string + { + return 'gitlab'; + } + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string + { + $about = Application::getAbout(); + + $report = []; + foreach ($reportSummary->getChanged() as $fileName => $change) { + foreach ($change['appliedFixers'] as $fixerName) { + $fixer = $this->fixers[$fixerName] ?? null; + + $report[] = [ + 'check_name' => 'PHP-CS-Fixer.'.$fixerName, + 'description' => null !== $fixer + ? $fixer->getDefinition()->getSummary() + : 'PHP-CS-Fixer.'.$fixerName.' (custom rule)', + 'content' => [ + 'body' => \sprintf( + "%s\n%s", + $about, + null !== $fixer + ? \sprintf( + 'Check [docs](https://cs.symfony.com/doc/rules/%s.html) for more information.', + substr($this->documentationLocator->getFixerDocumentationFileRelativePath($fixer), 0, -4), // -4 to drop `.rst` + ) + : 'Check performed with a custom rule.', + ), + ], + 'categories' => ['Style'], + 'fingerprint' => md5($fileName.$fixerName), + 'severity' => 'minor', + 'location' => [ + 'path' => $fileName, + 'lines' => self::getLines($this->diffParser->parse($change['diff'])), + ], + ]; + } + } + + $jsonString = json_encode($report, \JSON_THROW_ON_ERROR); + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($jsonString) : $jsonString; + } + + /** + * @param list $diffs + * + * @return array{begin: int, end: int} + */ + private static function getLines(array $diffs): array + { + if (isset($diffs[0])) { + $firstDiff = $diffs[0]; + + $firstChunk = \Closure::bind(static fn (Diff $diff) => array_shift($diff->chunks), null, $firstDiff)($firstDiff); + + if ($firstChunk instanceof Chunk) { + return self::getBeginEndForDiffChunk($firstChunk); + } + } + + return ['begin' => 0, 'end' => 0]; + } + + /** + * @return array{begin: int, end: int} + */ + private static function getBeginEndForDiffChunk(Chunk $chunk): array + { + $start = \Closure::bind(static fn (Chunk $chunk): int => $chunk->start, null, $chunk)($chunk); + $startRange = \Closure::bind(static fn (Chunk $chunk): int => $chunk->startRange, null, $chunk)($chunk); + $lines = \Closure::bind(static fn (Chunk $chunk): array => $chunk->lines, null, $chunk)($chunk); + + \assert(\count($lines) > 0); + + $firstModifiedLineOffset = array_find_key($lines, static function (Line $line): bool { + $type = \Closure::bind(static fn (Line $line): int => $line->type, null, $line)($line); + + return Line::UNCHANGED !== $type; + }); + \assert(\is_int($firstModifiedLineOffset)); + + return [ + // offset the start by where the first line is actually modified + 'begin' => $start + $firstModifiedLineOffset, + // it's not where last modification takes place, only where diff (with --context) ends + 'end' => $start + $startRange, + ]; + } + + /** + * @return array + */ + private function createFixers(): array + { + $fixers = []; + + foreach ($this->fixerFactory->getFixers() as $fixer) { + $fixers[$fixer->getName()] = $fixer; + } + + ksort($fixers); + + return $fixers; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php new file mode 100644 index 0000000..ad802a3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Console\Application; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class JsonReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'json'; + } + + public function generate(ReportSummary $reportSummary): string + { + $jsonFiles = []; + + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $jsonFile = ['name' => $file]; + + if ($reportSummary->shouldAddAppliedFixers()) { + $jsonFile['appliedFixers'] = $fixResult['appliedFixers']; + } + + if ('' !== $fixResult['diff']) { + $jsonFile['diff'] = $fixResult['diff']; + } + + $jsonFiles[] = $jsonFile; + } + + $json = [ + 'about' => Application::getAbout(), + 'files' => $jsonFiles, + 'time' => [ + 'total' => round($reportSummary->getTime() / 1_000, 3), + ], + 'memory' => round($reportSummary->getMemory() / 1_024 / 1_024, 3), + ]; + + $json = json_encode($json, \JSON_THROW_ON_ERROR); + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($json) : $json; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php new file mode 100644 index 0000000..7210e56 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php @@ -0,0 +1,153 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\Preg; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class JunitReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'junit'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + $testsuites = $dom->appendChild($dom->createElement('testsuites')); + + $testsuite = $testsuites->appendChild($dom->createElement('testsuite')); + \assert($testsuite instanceof \DOMElement); + + $testsuite->setAttribute('name', 'PHP CS Fixer'); + + $properties = $dom->createElement('properties'); + $property = $dom->createElement('property'); + $property->setAttribute('name', 'about'); + $property->setAttribute('value', Application::getAbout()); + $properties->appendChild($property); + $testsuite->appendChild($properties); + + if (\count($reportSummary->getChanged()) > 0) { + $this->createFailedTestCases($dom, $testsuite, $reportSummary); + } else { + $this->createSuccessTestCase($dom, $testsuite); + } + + if ($reportSummary->getTime() > 0) { + $testsuite->setAttribute( + 'time', + \sprintf( + '%.3f', + $reportSummary->getTime() / 1_000, + ), + ); + } + + $dom->formatOutput = true; + + $result = $dom->saveXML(); + if (false === $result) { + throw new \RuntimeException('Failed to generate XML output'); + } + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($result) : $result; + } + + private function createSuccessTestCase(\DOMDocument $dom, \DOMElement $testsuite): void + { + $testcase = $dom->createElement('testcase'); + $testcase->setAttribute('name', 'All OK'); + $testcase->setAttribute('assertions', '1'); + + $testsuite->appendChild($testcase); + $testsuite->setAttribute('tests', '1'); + $testsuite->setAttribute('assertions', '1'); + $testsuite->setAttribute('failures', '0'); + $testsuite->setAttribute('errors', '0'); + } + + private function createFailedTestCases(\DOMDocument $dom, \DOMElement $testsuite, ReportSummary $reportSummary): void + { + $assertionsCount = 0; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $testcase = $this->createFailedTestCase( + $dom, + $file, + $fixResult, + $reportSummary->shouldAddAppliedFixers(), + ); + $testsuite->appendChild($testcase); + $assertionsCount += (int) $testcase->getAttribute('assertions'); + } + + $testsuite->setAttribute('tests', (string) \count($reportSummary->getChanged())); + $testsuite->setAttribute('assertions', (string) $assertionsCount); + $testsuite->setAttribute('failures', (string) $assertionsCount); + $testsuite->setAttribute('errors', '0'); + } + + /** + * @param array{appliedFixers: list, diff: string} $fixResult + */ + private function createFailedTestCase(\DOMDocument $dom, string $file, array $fixResult, bool $shouldAddAppliedFixers): \DOMElement + { + $appliedFixersCount = \count($fixResult['appliedFixers']); + + $testName = str_replace('.', '_DOT_', Preg::replace('@\.'.pathinfo($file, \PATHINFO_EXTENSION).'$@', '', $file)); + + $testcase = $dom->createElement('testcase'); + $testcase->setAttribute('name', $testName); + $testcase->setAttribute('file', $file); + $testcase->setAttribute('assertions', (string) $appliedFixersCount); + + $failure = $dom->createElement('failure'); + $failure->setAttribute('type', 'code_style'); + $testcase->appendChild($failure); + + if ($shouldAddAppliedFixers) { + $failureContent = "applied fixers:\n---------------\n"; + + foreach ($fixResult['appliedFixers'] as $appliedFixer) { + $failureContent .= "* {$appliedFixer}\n"; + } + } else { + $failureContent = "Wrong code style\n"; + } + + if ('' !== $fixResult['diff']) { + $failureContent .= "\nDiff:\n---------------\n\n".$fixResult['diff']; + } + + $failure->appendChild($dom->createCDATASection(trim($failureContent))); + + return $testcase; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php new file mode 100644 index 0000000..14d39f5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReportSummary +{ + /** + * @var array, diff: string}> + */ + private array $changed; + + private int $filesCount; + + private int $time; + + private int $memory; + + private bool $addAppliedFixers; + + private bool $isDryRun; + + private bool $isDecoratedOutput; + + /** + * @param array, diff: string}> $changed + * @param int $time duration in milliseconds + * @param int $memory memory usage in bytes + */ + public function __construct( + array $changed, + int $filesCount, + int $time, + int $memory, + bool $addAppliedFixers, + bool $isDryRun, + bool $isDecoratedOutput + ) { + $this->changed = $changed; + $this->filesCount = $filesCount; + $this->time = $time; + $this->memory = $memory; + $this->addAppliedFixers = $addAppliedFixers; + $this->isDryRun = $isDryRun; + $this->isDecoratedOutput = $isDecoratedOutput; + } + + public function isDecoratedOutput(): bool + { + return $this->isDecoratedOutput; + } + + public function isDryRun(): bool + { + return $this->isDryRun; + } + + /** + * @return array, diff: string}> + */ + public function getChanged(): array + { + return $this->changed; + } + + public function getMemory(): int + { + return $this->memory; + } + + public function getTime(): int + { + return $this->time; + } + + public function getFilesCount(): int + { + return $this->filesCount; + } + + public function shouldAddAppliedFixers(): bool + { + return $this->addAppliedFixers; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php new file mode 100644 index 0000000..f33658b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php @@ -0,0 +1,95 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * @author Boris Gorbylev + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReporterFactory +{ + /** @var array */ + private array $reporters = []; + + public function registerBuiltInReporters(): self + { + /** @var null|list> $builtInReporters */ + static $builtInReporters; + + if (null === $builtInReporters) { + $builtInReporters = []; + + foreach (SymfonyFinder::create()->files()->name('*Reporter.php')->in(__DIR__) as $file) { + $relativeNamespace = $file->getRelativePath(); + + /** @var class-string $class */ + $class = \sprintf( + '%s\%s%s', + __NAMESPACE__, + '' !== $relativeNamespace ? $relativeNamespace.'\\' : '', + $file->getBasename('.php'), + ); + $builtInReporters[] = $class; + } + } + + foreach ($builtInReporters as $reporterClass) { + $this->registerReporter(new $reporterClass()); + } + + return $this; + } + + /** + * @return $this + */ + public function registerReporter(ReporterInterface $reporter): self + { + $format = $reporter->getFormat(); + + if (isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is already registered.', $format)); + } + + $this->reporters[$format] = $reporter; + + return $this; + } + + /** + * @return list + */ + public function getFormats(): array + { + $formats = array_keys($this->reporters); + sort($formats); + + return $formats; + } + + public function getReporter(string $format): ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is not registered.', $format)); + } + + return $this->reporters[$format]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php new file mode 100644 index 0000000..0d7ef22 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Boris Gorbylev + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ReporterInterface +{ + public function getFormat(): string; + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php new file mode 100644 index 0000000..9e898ec --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Differ\DiffConsoleFormatter; + +/** + * @author Boris Gorbylev + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TextReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'txt'; + } + + public function generate(ReportSummary $reportSummary): string + { + $output = ''; + + $identifiedFiles = 0; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + ++$identifiedFiles; + $output .= \sprintf('%4d) %s', $identifiedFiles, $file); + + if ($reportSummary->shouldAddAppliedFixers()) { + $output .= $this->getAppliedFixers( + $reportSummary->isDecoratedOutput(), + $fixResult['appliedFixers'], + ); + } + + $output .= $this->getDiff($reportSummary->isDecoratedOutput(), $fixResult['diff']); + $output .= \PHP_EOL; + } + + return $output.$this->getFooter( + $reportSummary->getTime(), + $identifiedFiles, + $reportSummary->getFilesCount(), + $reportSummary->getMemory(), + $reportSummary->isDryRun(), + ); + } + + /** + * @param list $appliedFixers + */ + private function getAppliedFixers(bool $isDecoratedOutput, array $appliedFixers): string + { + return \sprintf( + $isDecoratedOutput ? ' (%s)' : ' (%s)', + implode(', ', $appliedFixers), + ); + } + + private function getDiff(bool $isDecoratedOutput, string $diff): string + { + if ('' === $diff) { + return ''; + } + + $diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, \sprintf( + ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', + \PHP_EOL, + \PHP_EOL, + )); + + return \PHP_EOL.$diffFormatter->format($diff).\PHP_EOL; + } + + private function getFooter(int $time, int $identifiedFiles, int $files, int $memory, bool $isDryRun): string + { + return \PHP_EOL.\sprintf( + '%s %d of %d %s in %.3f seconds, %.2f MB memory used'.\PHP_EOL, + $isDryRun ? 'Found' : 'Fixed', + $identifiedFiles, + $files, + $isDryRun ? 'files that can be fixed' : 'files', + $time / 1_000, + $memory / 1_024 / 1_024, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php new file mode 100644 index 0000000..309a088 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php @@ -0,0 +1,143 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Console\Application; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Boris Gorbylev + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class XmlReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'xml'; + } + + public function generate(ReportSummary $reportSummary): string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + + $dom = new \DOMDocument('1.0', 'UTF-8'); + // new nodes should be added to this or existing children + $root = $dom->createElement('report'); + $dom->appendChild($root); + + $root->appendChild($this->createAboutElement($dom, Application::getAbout())); + + $filesXML = $dom->createElement('files'); + $root->appendChild($filesXML); + + $i = 1; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $fileXML = $dom->createElement('file'); + $fileXML->setAttribute('id', (string) $i++); + $fileXML->setAttribute('name', $file); + $filesXML->appendChild($fileXML); + + if ($reportSummary->shouldAddAppliedFixers()) { + $fileXML->appendChild( + $this->createAppliedFixersElement($dom, $fixResult['appliedFixers']), + ); + } + + if ('' !== $fixResult['diff']) { + $fileXML->appendChild($this->createDiffElement($dom, $fixResult['diff'])); + } + } + + if (0 !== $reportSummary->getTime()) { + $root->appendChild($this->createTimeElement($reportSummary->getTime(), $dom)); + } + + if (0 !== $reportSummary->getMemory()) { + $root->appendChild($this->createMemoryElement($reportSummary->getMemory(), $dom)); + } + + $dom->formatOutput = true; + + $result = $dom->saveXML(); + if (false === $result) { + throw new \RuntimeException('Failed to generate XML output'); + } + + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($result) : $result; + } + + /** + * @param list $appliedFixers + */ + private function createAppliedFixersElement(\DOMDocument $dom, array $appliedFixers): \DOMElement + { + $appliedFixersXML = $dom->createElement('applied_fixers'); + + foreach ($appliedFixers as $appliedFixer) { + $appliedFixerXML = $dom->createElement('applied_fixer'); + $appliedFixerXML->setAttribute('name', $appliedFixer); + $appliedFixersXML->appendChild($appliedFixerXML); + } + + return $appliedFixersXML; + } + + private function createDiffElement(\DOMDocument $dom, string $diff): \DOMElement + { + $diffXML = $dom->createElement('diff'); + $diffXML->appendChild($dom->createCDATASection($diff)); + + return $diffXML; + } + + private function createTimeElement(float $time, \DOMDocument $dom): \DOMElement + { + $time = round($time / 1_000, 3); + + $timeXML = $dom->createElement('time'); + $timeXML->setAttribute('unit', 's'); + $timeTotalXML = $dom->createElement('total'); + $timeTotalXML->setAttribute('value', (string) $time); + $timeXML->appendChild($timeTotalXML); + + return $timeXML; + } + + private function createMemoryElement(float $memory, \DOMDocument $dom): \DOMElement + { + $memory = round($memory / 1_024 / 1_024, 3); + + $memoryXML = $dom->createElement('memory'); + $memoryXML->setAttribute('value', (string) $memory); + $memoryXML->setAttribute('unit', 'MB'); + + return $memoryXML; + } + + private function createAboutElement(\DOMDocument $dom, string $about): \DOMElement + { + $xml = $dom->createElement('about'); + $xml->setAttribute('value', $about); + + return $xml; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/JsonReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/JsonReporter.php new file mode 100644 index 0000000..3981db4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/JsonReporter.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListRulesReport; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class JsonReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'json'; + } + + public function generate(ReportSummary $reportSummary): string + { + $fixers = $reportSummary->getFixers(); + + usort($fixers, static fn (FixerInterface $a, FixerInterface $b): int => $a->getName() <=> $b->getName()); + + $json = ['rules' => []]; + + foreach ($fixers as $fixer) { + $name = $fixer->getName(); + $json['rules'][$name] = [ + 'isRisky' => $fixer->isRisky(), + 'name' => $name, + 'summary' => $fixer->getDefinition()->getSummary(), + ]; + } + + return json_encode($json, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReportSummary.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReportSummary.php new file mode 100644 index 0000000..dbeff45 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReportSummary.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListRulesReport; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReportSummary +{ + /** + * @var list + */ + private array $fixers; + + /** + * @param list $fixers + */ + public function __construct(array $fixers) + { + $this->fixers = $fixers; + } + + /** + * @return list + */ + public function getFixers(): array + { + return $this->fixers; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterFactory.php new file mode 100644 index 0000000..bc39daf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterFactory.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListRulesReport; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReporterFactory +{ + /** + * @var array + */ + private array $reporters = []; + + public function getReporter(string $format): ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('The format "%s" is not defined.', $format)); + } + + return $this->reporters[$format]; + } + + /** + * @return list + */ + public function getFormats(): array + { + $formats = array_keys($this->reporters); + sort($formats); + + return $formats; + } + + /** + * @return $this + */ + public function registerBuiltInReporters(): self + { + $this + ->registerReporter(new JsonReporter()) + ->registerReporter(new TextReporter()) + ; + + return $this; + } + + /** + * @return $this + */ + public function registerReporter(ReporterInterface $reporter): self + { + $format = $reporter->getFormat(); + + if (isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is already registered.', $format)); + } + + $this->reporters[$format] = $reporter; + + return $this; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterInterface.php new file mode 100644 index 0000000..ad38fdb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/ReporterInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListRulesReport; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ReporterInterface +{ + public function getFormat(): string; + + public function generate(ReportSummary $reportSummary): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/TextReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/TextReporter.php new file mode 100644 index 0000000..0f82d9b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListRulesReport/TextReporter.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListRulesReport; + +use PhpCsFixer\Fixer\FixerInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TextReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'txt'; + } + + public function generate(ReportSummary $reportSummary): string + { + $fixers = $reportSummary->getFixers(); + + usort($fixers, static fn (FixerInterface $a, FixerInterface $b): int => $a->getName() <=> $b->getName()); + + $output = ''; + + foreach ($fixers as $i => $fixer) { + $output .= \sprintf('%3d) %s', $i + 1, $fixer->getName()).\PHP_EOL.' '.$fixer->getDefinition()->getSummary().\PHP_EOL; + + if ($fixer->isRisky()) { + $output .= ' Rule is risky.'.\PHP_EOL; + } + } + + return $output; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php new file mode 100644 index 0000000..327bf75 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class JsonReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'json'; + } + + public function generate(ReportSummary $reportSummary): string + { + $sets = $reportSummary->getSets(); + + usort($sets, static fn (RuleSetDefinitionInterface $a, RuleSetDefinitionInterface $b): int => $a->getName() <=> $b->getName()); + + $json = ['sets' => []]; + + foreach ($sets as $set) { + $setName = $set->getName(); + $json['sets'][$setName] = [ + 'description' => $set->getDescription(), + 'isRisky' => $set->isRisky(), + 'name' => $setName, + ]; + } + + return json_encode($json, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php new file mode 100644 index 0000000..733075a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReportSummary +{ + /** + * @var list + */ + private array $sets; + + /** + * @param list $sets + */ + public function __construct(array $sets) + { + $this->sets = $sets; + } + + /** + * @return list + */ + public function getSets(): array + { + return $this->sets; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php new file mode 100644 index 0000000..1380a8d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use Symfony\Component\Finder\Finder as SymfonyFinder; + +/** + * @author Boris Gorbylev + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReporterFactory +{ + /** + * @var array + */ + private array $reporters = []; + + /** + * @return $this + */ + public function registerBuiltInReporters(): self + { + /** @var null|list> $builtInReporters */ + static $builtInReporters; + + if (null === $builtInReporters) { + $builtInReporters = []; + + foreach (SymfonyFinder::create()->files()->name('*Reporter.php')->in(__DIR__) as $file) { + $relativeNamespace = $file->getRelativePath(); + + /** @var class-string $class */ + $class = \sprintf( + '%s\%s%s', + __NAMESPACE__, + '' !== $relativeNamespace ? $relativeNamespace.'\\' : '', + $file->getBasename('.php'), + ); + $builtInReporters[] = $class; + } + } + + foreach ($builtInReporters as $reporterClass) { + $this->registerReporter(new $reporterClass()); + } + + return $this; + } + + /** + * @return $this + */ + public function registerReporter(ReporterInterface $reporter): self + { + $format = $reporter->getFormat(); + + if (isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is already registered.', $format)); + } + + $this->reporters[$format] = $reporter; + + return $this; + } + + /** + * @return list + */ + public function getFormats(): array + { + $formats = array_keys($this->reporters); + sort($formats); + + return $formats; + } + + public function getReporter(string $format): ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is not registered.', $format)); + } + + return $this->reporters[$format]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php new file mode 100644 index 0000000..3e4f9eb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ReporterInterface +{ + public function getFormat(): string; + + /** + * Process changed files array. Returns generated report. + */ + public function generate(ReportSummary $reportSummary): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php new file mode 100644 index 0000000..6c03164 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TextReporter implements ReporterInterface +{ + public function getFormat(): string + { + return 'txt'; + } + + public function generate(ReportSummary $reportSummary): string + { + $sets = $reportSummary->getSets(); + + usort($sets, static fn (RuleSetDefinitionInterface $a, RuleSetDefinitionInterface $b): int => $a->getName() <=> $b->getName()); + + $output = ''; + + foreach ($sets as $i => $set) { + $output .= \sprintf('%2d) %s', $i + 1, $set->getName()).\PHP_EOL.' '.$set->getDescription().\PHP_EOL; + + if ($set->isRisky()) { + $output .= ' Set contains risky rules.'.\PHP_EOL; + } + } + + return $output; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php new file mode 100644 index 0000000..2381e22 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GithubClient implements GithubClientInterface +{ + private string $url; + + public function __construct(string $url = 'https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/tags') + { + $this->url = $url; + } + + public function getTags(): array + { + $result = @file_get_contents( + $this->url, + false, + stream_context_create([ + 'http' => [ + 'header' => 'User-Agent: PHP-CS-Fixer/PHP-CS-Fixer', + ], + ]), + ); + + if (false === $result) { + throw new \RuntimeException(\sprintf('Failed to load tags at "%s".', $this->url)); + } + + try { + /** + * @var list + */ + $result = json_decode($result, true, 512, \JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new \RuntimeException(\sprintf( + 'Failed to read response from "%s" as JSON: %s.', + $this->url, + $e->getMessage(), + )); + } + + return array_map( + static fn (array $tagData): string => $tagData['name'], + $result, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php new file mode 100644 index 0000000..b49297b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface GithubClientInterface +{ + /** + * @return list + */ + public function getTags(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php new file mode 100644 index 0000000..3d35a6b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +use Composer\Semver\Comparator; +use Composer\Semver\Semver; +use Composer\Semver\VersionParser; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NewVersionChecker implements NewVersionCheckerInterface +{ + private GithubClientInterface $githubClient; + + private VersionParser $versionParser; + + /** + * @var null|list + */ + private ?array $availableVersions = null; + + public function __construct(GithubClientInterface $githubClient) + { + $this->githubClient = $githubClient; + $this->versionParser = new VersionParser(); + } + + public function getLatestVersion(): string + { + $this->retrieveAvailableVersions(); + + \assert(isset($this->availableVersions[0])); + + return $this->availableVersions[0]; + } + + public function getLatestVersionOfMajor(int $majorVersion): ?string + { + $this->retrieveAvailableVersions(); + + $semverConstraint = '^'.$majorVersion; + + foreach ($this->availableVersions as $availableVersion) { + if (Semver::satisfies($availableVersion, $semverConstraint)) { + return $availableVersion; + } + } + + return null; + } + + public function compareVersions(string $versionA, string $versionB): int + { + $versionA = $this->versionParser->normalize($versionA); + $versionB = $this->versionParser->normalize($versionB); + + if (Comparator::lessThan($versionA, $versionB)) { + return -1; + } + + if (Comparator::greaterThan($versionA, $versionB)) { + return 1; + } + + return 0; + } + + private function retrieveAvailableVersions(): void + { + if (null !== $this->availableVersions) { + return; + } + + foreach ($this->githubClient->getTags() as $version) { + try { + $this->versionParser->normalize($version); + + if ('stable' === VersionParser::parseStability($version)) { + $this->availableVersions[] = $version; + } + } catch (\UnexpectedValueException $exception) { + // not a valid version tag + } + } + + $versions = Semver::rsort($this->availableVersions); + \assert(array_is_list($versions)); // Semver::rsort provides soft `array` type, let's validate and ensure proper type for SCA + + $this->availableVersions = $versions; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php new file mode 100644 index 0000000..a1be20d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface NewVersionCheckerInterface +{ + /** + * Returns the tag of the latest version. + */ + public function getLatestVersion(): string; + + /** + * Returns the tag of the latest minor/patch version of the given major version. + */ + public function getLatestVersionOfMajor(int $majorVersion): ?string; + + /** + * Returns -1, 0, or 1 if the first version is respectively less than, + * equal to, or greater than the second. + */ + public function compareVersions(string $versionA, string $versionB): int; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php new file mode 100644 index 0000000..2d74d94 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Console; + +use PhpCsFixer\ComposerJsonReader; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\ToolInfoInterface; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WarningsDetector +{ + private ToolInfoInterface $toolInfo; + + /** + * @var list + */ + private array $warnings = []; + + public function __construct(ToolInfoInterface $toolInfo) + { + $this->toolInfo = $toolInfo; + } + + public function detectOldMajor(): void + { + // @TODO 3.99 to be activated with new MAJOR release 4.0 + // $currentMajorVersion = \intval(explode('.', Application::VERSION)[0], 10); + // $nextMajorVersion = $currentMajorVersion + 1; + // $this->warnings[] = "You are running PHP CS Fixer v{$currentMajorVersion}, which is not maintained anymore. Please update to v{$nextMajorVersion}."; + // $this->warnings[] = "You may find an UPGRADE guide at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v{$nextMajorVersion}.0.0/UPGRADE-v{$nextMajorVersion}.md ."; + } + + public function detectOldVendor(): void + { + if ($this->toolInfo->isInstalledByComposer()) { + $details = $this->toolInfo->getComposerInstallationDetails(); + if (ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME === $details['name']) { + $this->warnings[] = \sprintf( + 'You are running PHP CS Fixer installed with old vendor `%s`. Please update to `%s`.', + ToolInfo::COMPOSER_LEGACY_PACKAGE_NAME, + ToolInfo::COMPOSER_PACKAGE_NAME, + ); + } + } + } + + public function detectNonMonolithic(): void + { + if (filter_var(getenv('PHP_CS_FIXER_NON_MONOLITHIC'), \FILTER_VALIDATE_BOOL)) { + $this->warnings[] = 'Processing non-monolithic files enabled, because `PHP_CS_FIXER_NON_MONOLITHIC` is set. Execution result may be unpredictable - non-monolithic files are not officially supported.'; + } + } + + public function detectHigherPhpVersion(): void + { + try { + $composerJsonReader = ComposerJsonReader::createSingleton(); + $minPhpVersion = $composerJsonReader->getPhp(); + + if (null === $minPhpVersion) { + $this->warnings[] = 'No PHP version requirement found in composer.json. It is recommended to specify a minimum PHP version supported by your project.'; + + return; + } + + $currentPhpVersion = \PHP_VERSION; + $currentPhpMajorMinor = \sprintf('%d.%d', \PHP_MAJOR_VERSION, \PHP_MINOR_VERSION); + + // Compare major.minor versions + if (version_compare($currentPhpMajorMinor, $minPhpVersion, '>')) { + $this->warnings[] = \sprintf( + 'You are running PHP CS Fixer on PHP %1$s, but the minimum PHP version supported by your project in composer.json is PHP %2$s. Executing PHP CS Fixer on newer PHP versions may introduce syntax or features not yet available in PHP %2$s, which could cause issues under that version. It is recommended to run PHP CS Fixer on PHP %2$s, to fit your project specifics.', + $currentPhpVersion, + $minPhpVersion, + ); + } + } catch (\Throwable $e) { + $this->warnings[] = \sprintf( + 'Unable to determine minimum PHP version supported by your project from composer.json: %s', + $e->getMessage(), + ); + } + } + + /** + * @return list + */ + public function getWarnings(): array + { + if (0 === \count($this->warnings)) { + return []; + } + + return array_values(array_unique(array_merge( + $this->warnings, + ['If you need help while solving warnings, ask at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/discussions/, we will help you!'], + ))); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/CustomRulesetsAwareConfigInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/CustomRulesetsAwareConfigInterface.php new file mode 100644 index 0000000..7294d9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/CustomRulesetsAwareConfigInterface.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @author Greg Korba + * + * @TODO 4.0 Include support for custom rulesets in main ConfigInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface CustomRulesetsAwareConfigInterface extends ConfigInterface +{ + /** + * Registers custom rule sets to be used the same way as built-in rule sets. + * + * @param list $ruleSets + * + * @todo v4 Introduce it in main ConfigInterface + * + * @return $this + */ + public function registerCustomRuleSets(array $ruleSets): ConfigInterface; + + /** + * @return list + */ + public function getCustomRuleSets(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php new file mode 100644 index 0000000..a2c1c49 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use Symfony\Component\Console\Formatter\OutputFormatter; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DiffConsoleFormatter +{ + private bool $isDecoratedOutput; + + private string $template; + + public function __construct(bool $isDecoratedOutput, string $template = '%s') + { + $this->isDecoratedOutput = $isDecoratedOutput; + $this->template = $template; + } + + public function format(string $diff, string $lineTemplate = '%s'): string + { + $isDecorated = $this->isDecoratedOutput; + + $template = $isDecorated + ? $this->template + : Preg::replace('/<[^<>]+>/', '', $this->template); + + return \sprintf( + $template, + implode( + \PHP_EOL, + array_map( + static function (string $line) use ($isDecorated, $lineTemplate): string { + if ($isDecorated) { + $count = 0; + $line = Preg::replaceCallback( + '/^([+\-@].*)/', + static function (array $matches): string { + \assert(isset($matches[0])); + if ('+' === $matches[0][0]) { + $colour = 'green'; + } elseif ('-' === $matches[0][0]) { + $colour = 'red'; + } else { + $colour = 'cyan'; + } + + return \sprintf('%s', $colour, OutputFormatter::escape($matches[0]), $colour); + }, + $line, + 1, + $count, + ); + + if (0 === $count) { + $line = OutputFormatter::escape($line); + } + } + + return \sprintf($lineTemplate, $line); + }, + Preg::split('#\R#u', $diff), + ), + ), + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php new file mode 100644 index 0000000..9f4c0bc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface DifferInterface +{ + /** + * Create diff. + */ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php new file mode 100644 index 0000000..ccb8a87 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use SebastianBergmann\Diff\Differ; +use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FullDiffer implements DifferInterface +{ + private Differ $differ; + + public function __construct() + { + $this->differ = new Differ(new StrictUnifiedDiffOutputBuilder([ + 'collapseRanges' => false, + 'commonLineThreshold' => 100, + 'contextLines' => 100, + 'fromFile' => 'Original', + 'toFile' => 'New', + ])); + } + + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + return $this->differ->diff($old, $new); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php new file mode 100644 index 0000000..2d9c9f0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullDiffer implements DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + return ''; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php new file mode 100644 index 0000000..4fdbbae --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use SebastianBergmann\Diff\Differ; +use SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class UnifiedDiffer implements DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null): string + { + if (null === $file) { + $options = [ + 'fromFile' => 'Original', + 'toFile' => 'New', + ]; + } else { + $filePath = $file->getRealPath(); + + if (Preg::match('/\s/', $filePath)) { + $filePath = '"'.$filePath.'"'; + } + + $options = [ + 'fromFile' => $filePath, + 'toFile' => $filePath, + ]; + } + + $differ = new Differ(new StrictUnifiedDiffOutputBuilder($options)); + + return $differ->diff($old, $new); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php new file mode 100644 index 0000000..5a47c71 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php @@ -0,0 +1,344 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; + +/** + * This represents an entire annotation from a docblock. + * + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Annotation implements \Stringable +{ + /** + * All the annotation tag names with types. + * + * @var non-empty-list + */ + public const TAGS_WITH_TYPES = [ + 'extends', + 'implements', + 'method', + 'param', + 'param-out', + 'phpstan-import-type', + 'phpstan-type', + 'phpstan-var', + 'property', + 'property-read', + 'property-write', + 'psalm-import-type', + 'psalm-type', + 'psalm-var', + 'return', + 'throws', + 'type', + 'var', + ]; + + /** + * The lines that make up the annotation. + * + * @var non-empty-list + */ + private array $lines; + + /** + * The position of the first line of the annotation in the docblock. + */ + private int $start; + + /** + * The position of the last line of the annotation in the docblock. + */ + private int $end; + + /** + * The associated tag. + */ + private ?Tag $tag = null; + + /** + * Lazy loaded, cached types content. + */ + private ?string $typesContent = null; + + /** + * The cached types. + * + * @var null|list + */ + private ?array $types = null; + + private ?NamespaceAnalysis $namespace = null; + + /** + * @var list + */ + private array $namespaceUses; + + /** + * Create a new line instance. + * + * @param non-empty-array $lines + * @param null|NamespaceAnalysis $namespace + * @param list $namespaceUses + */ + public function __construct(array $lines, $namespace = null, array $namespaceUses = []) + { + $this->lines = array_values($lines); + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + + $this->start = array_key_first($lines); + $this->end = array_key_last($lines); + } + + /** + * Get the string representation of object. + */ + public function __toString(): string + { + return $this->getContent(); + } + + /** + * Get all the annotation tag names with types. + * + * @return non-empty-list + * + * @deprecated Use `Annotation::TAGS_WITH_TYPES` constant instead + * + * @TODO 4.0 remove me + */ + public static function getTagsWithTypes(): array + { + return self::TAGS_WITH_TYPES; + } + + /** + * Get the start position of this annotation. + */ + public function getStart(): int + { + return $this->start; + } + + /** + * Get the end position of this annotation. + */ + public function getEnd(): int + { + return $this->end; + } + + /** + * Get the associated tag. + */ + public function getTag(): Tag + { + if (null === $this->tag) { + $this->tag = new Tag($this->lines[0]); + } + + return $this->tag; + } + + /** + * @internal + */ + public function getTypeExpression(): ?TypeExpression + { + $typesContent = $this->getTypesContent(); + + return null === $typesContent + ? null + : new TypeExpression($typesContent, $this->namespace, $this->namespaceUses); + } + + /** + * @internal + */ + public function getVariableName(): ?string + { + $type = preg_quote($this->getTypesContent() ?? '', '/'); + $regex = \sprintf( + '/@%s\s+(%s\s*)?(&\s*)?(\.{3}\s*)?(?\$%s)(?:.*|$)/', + $this->tag->getName(), + $type, + TypeExpression::REGEX_IDENTIFIER, + ); + + if (Preg::match($regex, $this->getContent(), $matches)) { + \assert(isset($matches['variable'])); + + return $matches['variable']; + } + + return null; + } + + /** + * Get the types associated with this annotation. + * + * @return list + */ + public function getTypes(): array + { + if (null === $this->types) { + $typeExpression = $this->getTypeExpression(); + $this->types = null === $typeExpression + ? [] + : $typeExpression->getTypes(); + } + + return $this->types; + } + + /** + * Set the types associated with this annotation. + * + * @param list $types + */ + public function setTypes(array $types): void + { + $origTypesContent = $this->getTypesContent(); + $newTypesContent = implode( + // Fallback to union type is provided for backward compatibility (previously glue was set to `|` by default even when type was not composite) + // @TODO Better handling for cases where type is fixed (original type is not composite, but was made composite during fix) + $this->getTypeExpression()->getTypesGlue() ?? '|', + $types, + ); + + if ($origTypesContent === $newTypesContent) { + return; + } + + $originalTypesLines = Preg::split('/([^\n\r]+\R*)/', $origTypesContent, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); + $newTypesLines = Preg::split('/([^\n\r]+\R*)/', $newTypesContent, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); + + \assert(\count($originalTypesLines) === \count($newTypesLines)); + + foreach ($newTypesLines as $index => $line) { + \assert(isset($originalTypesLines[$index])); + $pattern = '/'.preg_quote($originalTypesLines[$index], '/').'/'; + + \assert(isset($this->lines[$index])); + $this->lines[$index]->setContent(Preg::replace($pattern, $line, $this->lines[$index]->getContent(), 1)); + } + + $this->clearCache(); + } + + /** + * Get the normalized types associated with this annotation, so they can easily be compared. + * + * @return list + */ + public function getNormalizedTypes(): array + { + $typeExpression = $this->getTypeExpression(); + if (null === $typeExpression) { + return []; + } + + $normalizedTypeExpression = $typeExpression + ->mapTypes(static fn (TypeExpression $v) => new TypeExpression(strtolower($v->toString()), null, [])) + ->sortTypes(static fn (TypeExpression $a, TypeExpression $b) => $a->toString() <=> $b->toString()) + ; + + return $normalizedTypeExpression->getTypes(); + } + + /** + * Remove this annotation by removing all its lines. + */ + public function remove(): void + { + foreach ($this->lines as $line) { + if ($line->isTheStart() && $line->isTheEnd()) { + // Single line doc block, remove entirely + $line->remove(); + } elseif ($line->isTheStart()) { + // Multi line doc block, but start is on the same line as the first annotation, keep only the start + $content = Preg::replace('#(\s*/\*\*).*#', '$1', $line->getContent()); + + $line->setContent($content); + } elseif ($line->isTheEnd()) { + // Multi line doc block, but end is on the same line as the last annotation, keep only the end + $content = Preg::replace('#(\s*)\S.*(\*/.*)#', '$1$2', $line->getContent()); + + $line->setContent($content); + } else { + // Multi line doc block, neither start nor end on this line, can be removed safely + $line->remove(); + } + } + + $this->clearCache(); + } + + /** + * Get the annotation content. + */ + public function getContent(): string + { + return implode('', $this->lines); + } + + public function supportTypes(): bool + { + return \in_array($this->getTag()->getName(), self::TAGS_WITH_TYPES, true); + } + + /** + * Get the current types content. + * + * Be careful modifying the underlying line as that won't flush the cache. + */ + private function getTypesContent(): ?string + { + if (null === $this->typesContent) { + $name = $this->getTag()->getName(); + + if (!$this->supportTypes()) { + throw new \RuntimeException('This tag does not support types.'); + } + + if (Preg::match( + '{^(?:\h*\*|/\*\*)[\h*]*@'.$name.'\h+'.TypeExpression::REGEX_TYPES.'(?:(?:[*\h\v]|\&?[\.\$\s]).*)?\r?$}is', + $this->getContent(), + $matches, + )) { + \assert(isset($matches['types'])); + $this->typesContent = $matches['types']; + } + } + + return $this->typesContent; + } + + private function clearCache(): void + { + $this->types = null; + $this->typesContent = null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php new file mode 100644 index 0000000..f56c288 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php @@ -0,0 +1,255 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; + +/** + * This class represents a docblock. + * + * It internally splits it up into "lines" that we can manipulate. + * + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocBlock implements \Stringable +{ + /** + * @var list + */ + private array $lines = []; + + /** + * @var null|list + */ + private ?array $annotations = null; + + private ?NamespaceAnalysis $namespace; + + /** + * @var list + */ + private array $namespaceUses; + + /** + * @param list $namespaceUses + */ + public function __construct(string $content, ?NamespaceAnalysis $namespace = null, array $namespaceUses = []) + { + foreach (Preg::split('/([^\n\r]+\R*)/', $content, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE) as $line) { + $this->lines[] = new Line($line); + } + + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + } + + public function __toString(): string + { + return $this->getContent(); + } + + /** + * Get this docblock's lines. + * + * @return list + */ + public function getLines(): array + { + return $this->lines; + } + + /** + * Get a single line. + */ + public function getLine(int $pos): ?Line + { + return $this->lines[$pos] ?? null; + } + + /** + * Get this docblock's annotations. + * + * @return list + */ + public function getAnnotations(): array + { + if (null !== $this->annotations) { + return $this->annotations; + } + + $this->annotations = []; + $total = \count($this->lines); + + for ($index = 0; $index < $total; ++$index) { + \assert(isset($this->lines[$index])); + if ($this->lines[$index]->containsATag()) { + // get all the lines that make up the annotation + $lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), true); + \assert([] !== $lines); + $annotation = new Annotation($lines, $this->namespace, $this->namespaceUses); + // move the index to the end of the annotation to avoid + // checking it again because we know the lines inside the + // current annotation cannot be part of another annotation + $index = $annotation->getEnd(); + // add the current annotation to the list of annotations + $this->annotations[] = $annotation; + } + } + + return $this->annotations; + } + + public function isMultiLine(): bool + { + return 1 !== \count($this->lines); + } + + /** + * Take a one line doc block, and turn it into a multi line doc block. + */ + public function makeMultiLine(string $indent, string $lineEnd): void + { + if ($this->isMultiLine()) { + return; + } + + \assert(isset($this->lines[0])); + $lineContent = $this->getSingleLineDocBlockEntry($this->lines[0]); + + if ('' === $lineContent) { + $this->lines = [ + new Line('/**'.$lineEnd), + new Line($indent.' *'.$lineEnd), + new Line($indent.' */'), + ]; + + return; + } + + $this->lines = [ + new Line('/**'.$lineEnd), + new Line($indent.' * '.$lineContent.$lineEnd), + new Line($indent.' */'), + ]; + } + + public function makeSingleLine(): void + { + if (!$this->isMultiLine()) { + return; + } + + $usefulLines = array_filter( + $this->lines, + static fn (Line $line): bool => $line->containsUsefulContent(), + ); + + if (1 < \count($usefulLines)) { + return; + } + + $lineContent = ''; + if (\count($usefulLines) > 0) { + $lineContent = $this->getSingleLineDocBlockEntry(array_shift($usefulLines)); + } + + $this->lines = [new Line('/** '.$lineContent.' */')]; + } + + public function getAnnotation(int $pos): ?Annotation + { + $annotations = $this->getAnnotations(); + + return $annotations[$pos] ?? null; + } + + /** + * Get specific types of annotations only. + * + * @param list|string $types + * + * @return list + */ + public function getAnnotationsOfType($types): array + { + $typesToSearchFor = (array) $types; + + $annotations = []; + + foreach ($this->getAnnotations() as $annotation) { + $tagName = $annotation->getTag()->getName(); + if (\in_array($tagName, $typesToSearchFor, true)) { + $annotations[] = $annotation; + } + } + + return $annotations; + } + + /** + * Get the actual content of this docblock. + */ + public function getContent(): string + { + return implode('', $this->lines); + } + + private function findAnnotationLength(int $start): int + { + $index = $start; + + while (($line = $this->getLine(++$index)) !== null) { + if ($line->containsATag()) { + // we've 100% reached the end of the description if we get here + break; + } + + if (!$line->containsUsefulContent()) { + // if next line is also non-useful, or contains a tag, then we're done here + $next = $this->getLine($index + 1); + if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) { + break; + } + // otherwise, continue, the annotation must have contained a blank line in its description + } + } + + return $index - $start; + } + + private function getSingleLineDocBlockEntry(Line $line): string + { + $lineString = $line->getContent(); + + if ('' === $lineString) { + return $lineString; + } + + $lineString = str_replace('*/', '', $lineString); + $lineString = trim($lineString); + + if (str_starts_with($lineString, '/**')) { + $lineString = substr($lineString, 3); + } elseif (str_starts_with($lineString, '*')) { + $lineString = substr($lineString, 1); + } + + return trim($lineString); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php new file mode 100644 index 0000000..d471759 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php @@ -0,0 +1,130 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; + +/** + * This represents a line of a docblock. + * + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Line implements \Stringable +{ + /** + * The content of this line. + */ + private string $content; + + /** + * Create a new line instance. + */ + public function __construct(string $content) + { + $this->content = $content; + } + + /** + * Get the string representation of object. + */ + public function __toString(): string + { + return $this->content; + } + + /** + * Get the content of this line. + */ + public function getContent(): string + { + return $this->content; + } + + /** + * Does this line contain useful content? + * + * If the line contains text or tags, then this is true. + */ + public function containsUsefulContent(): bool + { + return Preg::match('/\*\s*\S+/', $this->content) && '' !== trim(str_replace(['/', '*'], ' ', $this->content)); + } + + /** + * Does the line contain a tag? + * + * If this is true, then it must be the first line of an annotation. + */ + public function containsATag(): bool + { + return Preg::match('/\*\s*@/', $this->content); + } + + /** + * Is the line the start of a docblock? + */ + public function isTheStart(): bool + { + return str_contains($this->content, '/**'); + } + + /** + * Is the line the end of a docblock? + */ + public function isTheEnd(): bool + { + return str_contains($this->content, '*/'); + } + + /** + * Set the content of this line. + */ + public function setContent(string $content): void + { + $this->content = $content; + } + + /** + * Remove this line by clearing its contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function remove(): void + { + $this->content = ''; + } + + /** + * Append a blank docblock line to this line's contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function addBlank(): void + { + $matched = Preg::match('/^(\h*\*)[^\r\n]*(\r?\n)$/', $this->content, $matches); + + if (!$matched) { + return; + } + + $this->content .= $matches[1].$matches[2]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php new file mode 100644 index 0000000..b6f183f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +/** + * This class represents a short description (aka summary) of a docblock. + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ShortDescription +{ + /** + * The docblock containing the short description. + */ + private DocBlock $doc; + + public function __construct(DocBlock $doc) + { + $this->doc = $doc; + } + + /** + * Get the line index of the line containing the end of the short + * description, if present. + */ + public function getEnd(): ?int + { + $reachedContent = false; + + foreach ($this->doc->getLines() as $index => $line) { + // we went past a description, then hit a tag or blank line, so + // the last line of the description must be the one before this one + if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) { + return $index - 1; + } + + // no short description was found + if ($line->containsATag()) { + return null; + } + + // we've reached content, but need to check the next lines too + // in case the short description is multi-line + if ($line->containsUsefulContent()) { + $reachedContent = true; + } + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php new file mode 100644 index 0000000..1535ce5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; + +/** + * This represents a tag, as defined by the proposed PSR PHPDoc standard. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Tag +{ + /** + * All the tags defined by the proposed PSR PHPDoc standard. + */ + public const PSR_STANDARD_TAGS = [ + 'api', 'author', 'category', 'copyright', 'deprecated', 'example', + 'global', 'internal', 'license', 'link', 'method', 'package', 'param', + 'property', 'property-read', 'property-write', 'return', 'see', + 'since', 'subpackage', 'throws', 'todo', 'uses', 'var', 'version', + ]; + + /** + * The line containing the tag. + */ + private Line $line; + + /** + * The cached tag name. + */ + private ?string $name = null; + + /** + * Create a new tag instance. + */ + public function __construct(Line $line) + { + $this->line = $line; + } + + /** + * Get the tag name. + * + * This may be "param", or "return", etc. + */ + public function getName(): string + { + if (null === $this->name) { + Preg::matchAll('/@[a-zA-Z0-9_-]+(?=\s|$)/', $this->line->getContent(), $matches); + + if (isset($matches[0][0])) { + $this->name = ltrim($matches[0][0], '@'); + } else { + $this->name = 'other'; + } + } + + return $this->name; + } + + /** + * Set the tag name. + * + * This will also be persisted to the upstream line and annotation. + */ + public function setName(string $name): void + { + $current = $this->getName(); + + if ('other' === $current) { + throw new \RuntimeException('Cannot set name on unknown tag.'); + } + + $this->line->setContent(Preg::replace("/@{$current}/", "@{$name}", $this->line->getContent(), 1)); + + $this->name = $name; + } + + /** + * Is the tag a known tag? + * + * This is defined by if it exists in the proposed PSR PHPDoc standard. + */ + public function valid(): bool + { + return \in_array($this->getName(), self::PSR_STANDARD_TAGS, true); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php new file mode 100644 index 0000000..d5de1a4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +/** + * This class is responsible for comparing tags to see if they should be kept + * together, or kept apart. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @deprecated + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TagComparator +{ + /** + * Groups of tags that should be allowed to immediately follow each other. + * + * @var non-empty-list> + * + * @internal + */ + public const DEFAULT_GROUPS = [ + ['deprecated', 'link', 'see', 'since'], + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ]; + + /** + * Should the given tags be kept together, or kept apart? + * + * @param list> $groups + */ + public static function shouldBeTogether(Tag $first, Tag $second, array $groups = self::DEFAULT_GROUPS): bool + { + @trigger_error('Method '.__METHOD__.' is deprecated and will be removed in version 4.0.', \E_USER_DEPRECATED); + + $firstName = $first->getName(); + $secondName = $second->getName(); + + if ($firstName === $secondName) { + return true; + } + + foreach ($groups as $group) { + if (\in_array($firstName, $group, true) && \in_array($secondName, $group, true)) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php new file mode 100644 index 0000000..18cff02 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php @@ -0,0 +1,920 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Utils; + +/** + * @author Michael Vorisek + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeExpression +{ + /** + * Regex to match any PHP identifier. + * + * @internal + */ + public const REGEX_IDENTIFIER = '(?:(?!(?(?x) # one or several types separated by `|` or `&` +'.self::REGEX_TYPE.' + (?: + \h*(?[|&])\h* + (?&type) + )*+ + )'; + + /** + * Based on: + * - https://github.com/phpstan/phpdoc-parser/blob/1.26.0/doc/grammars/type.abnf fuzzing grammar + * - and https://github.com/phpstan/phpdoc-parser/blob/1.26.0/src/Parser/PhpDocParser.php parser impl. + */ + private const REGEX_TYPE = '(?(?x) # single type + (?:co(?:ntra)?variant\h+)? + (?\??\h*) + (?: + (? + (?(?i)(?:array|list|object)(?-i)) + (?\h*\{[\h\v*]*) + (? + (? + (?(?:(?&constant)|(?&identifier)|(?&name))\h*\??\h*:\h*|) + (?(?&types_inner)) + ) + (?: + \h*,[\h\v*]* + (?&array_shape_inner) + )*+ + (?:\h*,|(?!(?&array_shape_unsealed_variadic))) + |) + (? # unsealed array shape, e.g. `...`. `...` + (?\h*\.\.\.) + (? + (?\h*<\h*) + (?(?&types_inner)) + (?: + (?\h*,\h*) + (?(?&array_shape_unsealed_type_a)) + |) + \h*> + |) + |) + [\h\v*]*\} + ) + | + (? # callable syntax, e.g. `callable(string, int...): bool`, `\Closure(T, int): T` + (?(?&name)) + (? + (?\h*<\h*) + (? + (? + (? + (?&identifier) + ) + (? # template bound + \h+(?i)(?of|as)(?-i)\h+ + (?(?&types_inner)) + |) + (? # template default + \h*=\h* + (?(?&types_inner)) + |) + ) + (?: + \h*,\h* + (?&callable_template_inner) + )*+ + ) + \h*> + (?=\h*\() + |) + (?\h*\(\h*) + (? + (? + (?(?&types_inner)) + (?\h*&|) + (?\h*\.\.\.|) + (?\h*\$(?&identifier)|) + (?\h*=|) + ) + (?: + \h*,\h* + (?&callable_argument) + )*+ + (?:\h*,)? + |) + \h*\) + (?: + \h*\:\h* + (?(?&type)) + )? + ) + | + (? # generic syntax, e.g.: `array` + (?(?&name)) + (?\h*<[\h\v*]*) + (? + (?&types_inner) + (?: + \h*,[\h\v*]* + (?&types_inner) + )*+ + (?:\h*,)? + ) + [\h\v*]*> + ) + | + (? # class constants with optional wildcard, e.g.: `Foo::*`, `Foo::CONST_A`, `FOO::CONST_*` + (?(?&name)) + ::\*?(?:(?&identifier)\*?)* + ) + | + (? # single constant value (case insensitive), e.g.: 1, -1.8E+6, `\'a\'` + (?i) + # all sorts of numbers: with or without sign, supports literal separator and several numeric systems, + # e.g.: 1, +1.1, 1., .1, -1, 123E+8, 123_456_789, 0x7Fb4, 0b0110, 0o777 + [+-]?(?: + (?:0b[01]++(?:_[01]++)*+) + | (?:0o[0-7]++(?:_[0-7]++)*+) + | (?:0x[\da-f]++(?:_[\da-f]++)*+) + | (?:(?\d++(?:_\d++)*+)|(?=\.\d)) + (?:\.(?&constant_digits)|(?<=\d)\.)?+ + (?:e[+-]?(?&constant_digits))?+ + ) + | \'(?:[^\'\\\]|\\\.)*+\' + | "(?:[^"\\\]|\\\.)*+" + (?-i) + ) + | + (? # self reference, e.g.: $this, $self, @static + (?i) + [@$](?:this | self | static) + (?-i) + ) + | + (? # full name, e.g.: `int`, `\DateTime`, `\Foo\Bar`, `positive-int` + \\\?+ + (?'.self::REGEX_IDENTIFIER.') + (?:[\\\\\-](?&identifier))*+ + ) + | + (? # parenthesized type, e.g.: `(int)`, `(int|\stdClass)` + (? + \(\h* + ) + (?: + (? + (?&types_inner) + ) + | + (? # conditional type, e.g.: `$foo is \Throwable ? false : $foo` + (? + (?:\$(?&identifier)) + | + (?(?&types_inner)) + ) + (? + \h+(?i)is(?:\h+not)?(?-i)\h+ + ) + (?(?&types_inner)) + (?\h*\?\h*) + (?(?&types_inner)) + (?\h*:\h*) + (?(?&types_inner)) + ) + ) + \h*\) + ) + ) + (? # array, e.g.: `string[]`, `array[][]` + (\h*\[\h*\])* + ) + (?:(?=1)0 + (?(?> + (?&type) + (?: + \h*[|&]\h* + (?&type) + )*+ + )) + |) + )'; + + private const ALIASES = [ + 'boolean' => 'bool', + 'callback' => 'callable', + 'double' => 'float', + 'false' => 'bool', + 'integer' => 'int', + 'list' => 'array', + 'real' => 'float', + 'true' => 'bool', + ]; + + private string $value; + + private bool $isCompositeType; + + /** @var null|'&'|'|' */ + private ?string $typesGlue = null; + + /** @var list */ + private array $innerTypeExpressions = []; + + private ?NamespaceAnalysis $namespace; + + /** @var list */ + private array $namespaceUses; + + /** + * @param list $namespaceUses + */ + public function __construct(string $value, ?NamespaceAnalysis $namespace, array $namespaceUses) + { + $this->value = $value; + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + + $this->parse(); + } + + public function toString(): string + { + return $this->value; + } + + /** + * @return list + */ + public function getTypes(): array + { + if ($this->isCompositeType) { + return array_map( + static fn (array $type) => $type['expression']->toString(), + $this->innerTypeExpressions, + ); + } + + return [$this->value]; + } + + /** + * Determines if type expression is a composite type (union or intersection). + */ + public function isCompositeType(): bool + { + return $this->isCompositeType; + } + + public function isUnionType(): bool + { + return $this->isCompositeType && '|' === $this->typesGlue; + } + + public function isIntersectionType(): bool + { + return $this->isCompositeType && '&' === $this->typesGlue; + } + + /** + * @return null|'&'|'|' + */ + public function getTypesGlue(): ?string + { + return $this->typesGlue; + } + + /** + * @param \Closure(self): self $callback + */ + public function mapTypes(\Closure $callback): self + { + $value = $this->value; + $startIndexOffset = 0; + + foreach ($this->innerTypeExpressions as [ + 'start_index' => $startIndexOrig, + 'expression' => $inner, + ]) { + $innerValueOrig = $inner->value; + + $inner = $inner->mapTypes($callback); + + if ($inner->value !== $innerValueOrig) { + $value = substr_replace( + $value, + $inner->value, + $startIndexOrig + $startIndexOffset, + \strlen($innerValueOrig), + ); + + $startIndexOffset += \strlen($inner->value) - \strlen($innerValueOrig); + } + } + + $type = $value === $this->value + ? $this + : $this->inner($value); + + return $callback($type); + } + + /** + * @param \Closure(self): void $callback + */ + public function walkTypes(\Closure $callback): void + { + $this->mapTypes(static function (self $type) use ($callback) { + $valueOrig = $type->value; + $callback($type); + \assert($type->value === $valueOrig); + + return $type; + }); + } + + /** + * @param \Closure(self, self): (-1|0|1) $compareCallback + */ + public function sortTypes(\Closure $compareCallback): self + { + return $this->mapTypes(function (self $type) use ($compareCallback): self { + if (!$type->isCompositeType) { + return $type; + } + + $innerTypeExpressions = Utils::stableSort( + $type->innerTypeExpressions, + static fn (array $v): self => $v['expression'], + $compareCallback, + ); + + if ($innerTypeExpressions !== $type->innerTypeExpressions) { + $value = implode( + $type->getTypesGlue(), + array_map(static fn (array $v): string => $v['expression']->toString(), $innerTypeExpressions), + ); + + return $this->inner($value); + } + + return $type; + }); + } + + public function removeDuplicateTypes(): self + { + return $this->mapTypes(function (self $type): self { + if (!$type->isCompositeType) { + return $type; + } + + $seenNormalized = []; + $uniqueTypeExpressions = []; + + foreach ($type->innerTypeExpressions as $innerType) { + $normalized = $innerType['expression'] + ->sortTypes(static fn (self $a, self $b): int => $a->toString() <=> $b->toString()) + ->toString() + ; + + if (!\in_array($normalized, $seenNormalized, true)) { + $seenNormalized[] = $normalized; + $uniqueTypeExpressions[] = $innerType['expression']; + } + } + + $value = implode( + $type->getTypesGlue(), + array_map(static fn (self $expr): string => $expr->toString(), $uniqueTypeExpressions), + ); + + return $this->inner($value); + }); + } + + public function getCommonType(): ?string + { + $mainType = null; + + foreach ($this->getTypes() as $type) { + if ('null' === $type) { + continue; + } + + if (str_starts_with($type, '?')) { + $type = substr($type, 1); + } + + if (Preg::match('/\[\h*\]$/', $type)) { + $type = 'array'; + } elseif (Preg::match('/^(.+?)\h*[<{(]/', $type, $matches)) { + $type = $matches[1]; + } + + if (isset(self::ALIASES[$type])) { + $type = self::ALIASES[$type]; + } + + if (null === $mainType || $type === $mainType) { + $mainType = $type; + + continue; + } + + $mainType = $this->getParentType($type, $mainType); + + if (null === $mainType) { + return null; + } + } + + return $mainType; + } + + public function allowsNull(): bool + { + foreach ($this->getTypes() as $type) { + if (\in_array($type, ['null', 'mixed'], true) || str_starts_with($type, '?')) { + return true; + } + } + + return false; + } + + private function parse(): void + { + $seenGlues = null; + $innerValues = []; + + $index = 0; + while (true) { + Preg::match( + '{\G'.self::REGEX_TYPE.'(?\h*(?[|&])\h*(?!$)|$)}', + $this->value, + $matches, + \PREG_OFFSET_CAPTURE, + $index, + ); + + if ([] === $matches) { + throw new \Exception('Unable to parse phpdoc type '.var_export($this->value, true)); + } + + \assert(isset($matches[0], $matches['type'])); + + if (null === $seenGlues) { + if (($matches['glue'][0] ?? '') === '') { + break; + } + + $seenGlues = ['|' => false, '&' => false]; + } + + if (($matches['glue'][0] ?? '') !== '') { + \assert(isset($seenGlues[$matches['glue'][0]])); + $seenGlues[$matches['glue'][0]] = true; + } + + $innerValues[] = [ + 'start_index' => $index, + 'value' => $matches['type'][0], + 'next_glue' => $matches['glue'][0] ?? null, + 'next_glue_raw' => $matches['glue_raw'][0] ?? null, + ]; + + $consumedValueLength = \strlen($matches[0][0]); + $index += $consumedValueLength; + + if (\strlen($this->value) <= $index) { + \assert(\strlen($this->value) === $index); + + $seenGlues = array_filter($seenGlues); + \assert([] !== $seenGlues); + + $this->isCompositeType = true; + $this->typesGlue = array_key_first($seenGlues); + + if (1 === \count($seenGlues)) { + foreach ($innerValues as $innerValue) { + $this->innerTypeExpressions[] = [ + 'start_index' => $innerValue['start_index'], + 'expression' => $this->inner($innerValue['value']), + ]; + } + } else { + for ($i = 0; $i < \count($innerValues); ++$i) { + $innerStartIndex = $innerValues[$i]['start_index']; + $innerValue = ''; + while (true) { + $innerValue .= $innerValues[$i]['value']; + + if (($innerValues[$i]['next_glue'] ?? $this->typesGlue) === $this->typesGlue) { + break; + } + + $innerValue .= $innerValues[$i]['next_glue_raw']; + + ++$i; + \assert(isset($innerValues[$i])); // for PHPStan + } + + $this->innerTypeExpressions[] = [ + 'start_index' => $innerStartIndex, + 'expression' => $this->inner($innerValue), + ]; + } + } + + return; + } + } + + $this->isCompositeType = false; + + \assert(isset($matches['nullable'], $matches['array'], $matches['class_constant'])); + + if ('' !== $matches['nullable'][0]) { + $this->innerTypeExpressions[] = [ + 'start_index' => \strlen($matches['nullable'][0]), + 'expression' => $this->inner(substr($matches['type'][0], \strlen($matches['nullable'][0]))), + ]; + } elseif ('' !== $matches['array'][0]) { + $this->innerTypeExpressions[] = [ + 'start_index' => 0, + 'expression' => $this->inner(substr($matches['type'][0], 0, -\strlen($matches['array'][0]))), + ]; + } elseif ('' !== ($matches['generic'][0] ?? '') && 0 === $matches['generic'][1]) { + \assert(isset($matches['generic_name'], $matches['generic_start'], $matches['generic_types'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => 0, + 'expression' => $this->inner($matches['generic_name'][0]), + ]; + + $this->parseCommaSeparatedInnerTypes( + \strlen($matches['generic_name'][0]) + \strlen($matches['generic_start'][0]), + $matches['generic_types'][0], + ); + } elseif ('' !== ($matches['callable'][0] ?? '') && 0 === $matches['callable'][1]) { + \assert(isset($matches['callable_name'], $matches['callable_template'], $matches['callable_start'], $matches['callable_arguments'], $matches['callable_template_start'], $matches['callable_template_inners'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => 0, + 'expression' => $this->inner($matches['callable_name'][0]), + ]; + + $this->parseCallableTemplateInnerTypes( + \strlen($matches['callable_name'][0]) + + \strlen($matches['callable_template_start'][0]), + $matches['callable_template_inners'][0], + ); + + $this->parseCallableArgumentTypes( + \strlen($matches['callable_name'][0]) + + \strlen($matches['callable_template'][0]) + + \strlen($matches['callable_start'][0]), + $matches['callable_arguments'][0], + ); + + if ('' !== ($matches['callable_return'][0] ?? '')) { + $this->innerTypeExpressions[] = [ + 'start_index' => \strlen($this->value) - \strlen($matches['callable_return'][0]), + 'expression' => $this->inner($matches['callable_return'][0]), + ]; + } + } elseif ('' !== ($matches['array_shape'][0] ?? '') && 0 === $matches['array_shape'][1]) { + \assert(isset($matches['array_shape_name'], $matches['array_shape_start'], $matches['array_shape_inners'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => 0, + 'expression' => $this->inner($matches['array_shape_name'][0]), + ]; + + $nextIndex = \strlen($matches['array_shape_name'][0]) + \strlen($matches['array_shape_start'][0]); + + $this->parseArrayShapeInnerTypes( + $nextIndex, + $matches['array_shape_inners'][0], + ); + + if ('' !== ($matches['array_shape_unsealed_type'][0] ?? '')) { + \assert(isset($matches['array_shape_unsealed_variadic'], $matches['array_shape_unsealed_type_start'], $matches['array_shape_unsealed_type_a'])); + + $nextIndex += \strlen($matches['array_shape_inners'][0]) + + \strlen($matches['array_shape_unsealed_variadic'][0]) + + \strlen($matches['array_shape_unsealed_type_start'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $nextIndex, + 'expression' => $this->inner($matches['array_shape_unsealed_type_a'][0]), + ]; + + if ('' !== ($matches['array_shape_unsealed_type_b'][0] ?? '')) { + \assert(isset($matches['array_shape_unsealed_type_comma'])); + + $nextIndex += \strlen($matches['array_shape_unsealed_type_a'][0]) + + \strlen($matches['array_shape_unsealed_type_comma'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $nextIndex, + 'expression' => $this->inner($matches['array_shape_unsealed_type_b'][0]), + ]; + } + } + } elseif ('' !== ($matches['parenthesized'][0] ?? '') && 0 === $matches['parenthesized'][1]) { + \assert(isset($matches['parenthesized_start'])); + $index = \strlen($matches['parenthesized_start'][0]); + + if ('' !== ($matches['conditional'][0] ?? '')) { + \assert(isset($matches['conditional_cond_left'], $matches['conditional_cond_middle'], $matches['conditional_cond_right_types'], $matches['conditional_true_start'], $matches['conditional_true_types'], $matches['conditional_false_start'], $matches['conditional_false_types'])); + + if ('' !== ($matches['conditional_cond_left_types'][0] ?? '')) { + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_cond_left_types'][0]), + ]; + } + + $index += \strlen($matches['conditional_cond_left'][0]) + \strlen($matches['conditional_cond_middle'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_cond_right_types'][0]), + ]; + + $index += \strlen($matches['conditional_cond_right_types'][0]) + \strlen($matches['conditional_true_start'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_true_types'][0]), + ]; + + $index += \strlen($matches['conditional_true_types'][0]) + \strlen($matches['conditional_false_start'][0]); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['conditional_false_types'][0]), + ]; + } else { + \assert(isset($matches['parenthesized_types'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $index, + 'expression' => $this->inner($matches['parenthesized_types'][0]), + ]; + } + } elseif ('' !== $matches['class_constant'][0]) { + \assert(isset($matches['class_constant_name'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => 0, + 'expression' => $this->inner($matches['class_constant_name'][0]), + ]; + } + } + + private function parseCommaSeparatedInnerTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G'.self::REGEX_TYPES.'(?:\h*,[\h\v*]*|$)}', + $value, + $matches, + 0, + $index, + ); + + \assert(isset($matches[0], $matches['types'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index, + 'expression' => $this->inner($matches['types']), + ]; + + $index += \strlen($matches[0]); + } + } + + private function parseCallableTemplateInnerTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G(?:(?=1)0'.self::REGEX_TYPES.'|(?<_callable_template_inner>(?&callable_template_inner))(?:\h*,\h*|$))}', + $value, + $prematches, + 0, + $index, + ); + \assert(isset($prematches[0], $prematches['_callable_template_inner'])); + $consumedValue = $prematches['_callable_template_inner']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + + $addedPrefix = 'Closure<'; + Preg::match( + '{^'.self::REGEX_TYPES.'$}', + $addedPrefix.$consumedValue.'>(): void', + $matches, + \PREG_OFFSET_CAPTURE, + ); + + \assert(isset($matches['callable_template_inner_b'], $matches['callable_template_inner_d'])); + + if ('' !== $matches['callable_template_inner_b'][0]) { + \assert(isset($matches['callable_template_inner_b_types'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index + $matches['callable_template_inner_b_types'][1] + - \strlen($addedPrefix), + 'expression' => $this->inner($matches['callable_template_inner_b_types'][0]), + ]; + } + + if ('' !== $matches['callable_template_inner_d'][0]) { + \assert(isset($matches['callable_template_inner_d_types'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index + $matches['callable_template_inner_d_types'][1] + - \strlen($addedPrefix), + 'expression' => $this->inner($matches['callable_template_inner_d_types'][0]), + ]; + } + + $index += $consumedValueLength + $consumedCommaLength; + } + } + + private function parseCallableArgumentTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G(?:(?=1)0'.self::REGEX_TYPES.'|(?<_callable_argument>(?&callable_argument))(?:\h*,\h*|$))}', + $value, + $prematches, + 0, + $index, + ); + \assert(isset($prematches[0], $prematches['_callable_argument'])); + $consumedValue = $prematches['_callable_argument']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + + $addedPrefix = 'Closure('; + Preg::match( + '{^'.self::REGEX_TYPES.'$}', + $addedPrefix.$consumedValue.'): void', + $matches, + \PREG_OFFSET_CAPTURE, + ); + + \assert(isset($matches['callable_argument_type'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index, + 'expression' => $this->inner($matches['callable_argument_type'][0]), + ]; + + $index += $consumedValueLength + $consumedCommaLength; + } + } + + private function parseArrayShapeInnerTypes(int $startIndex, string $value): void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match( + '{\G(?:(?=1)0'.self::REGEX_TYPES.'|(?<_array_shape_inner>(?&array_shape_inner))(?:\h*,[\h\v*]*|$))}', + $value, + $prematches, + 0, + $index, + ); + \assert(isset($prematches[0], $prematches['_array_shape_inner'])); + $consumedValue = $prematches['_array_shape_inner']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + + $addedPrefix = 'array{'; + Preg::match( + '{^'.self::REGEX_TYPES.'$}', + $addedPrefix.$consumedValue.'}', + $matches, + \PREG_OFFSET_CAPTURE, + ); + + \assert(isset($matches['array_shape_inner_value'])); + + $this->innerTypeExpressions[] = [ + 'start_index' => $startIndex + $index + $matches['array_shape_inner_value'][1] + - \strlen($addedPrefix), + 'expression' => $this->inner($matches['array_shape_inner_value'][0]), + ]; + + $index += $consumedValueLength + $consumedCommaLength; + } + } + + private function inner(string $value): self + { + return new self($value, $this->namespace, $this->namespaceUses); + } + + private function getParentType(string $type1, string $type2): ?string + { + $types = [ + $this->normalize($type1), + $this->normalize($type2), + ]; + natcasesort($types); + $types = implode('|', $types); + + $parents = [ + 'array|Traversable' => 'iterable', + 'array|iterable' => 'iterable', + 'iterable|Traversable' => 'iterable', + 'self|static' => 'self', + ]; + + return $parents[$types] ?? null; + } + + private function normalize(string $type): string + { + if (isset(self::ALIASES[$type])) { + return self::ALIASES[$type]; + } + + if (\in_array($type, [ + 'array', + 'bool', + 'callable', + 'false', + 'float', + 'int', + 'iterable', + 'mixed', + 'never', + 'null', + 'object', + 'resource', + 'string', + 'true', + 'void', + ], true)) { + return $type; + } + + if (Preg::match('/\[\]$/', $type)) { + return 'array'; + } + + if (Preg::match('/^(.+?)namespaceUses as $namespaceUse) { + if ($namespaceUse->getShortName() === $type) { + return $namespaceUse->getFullName(); + } + } + + if (null === $this->namespace || $this->namespace->isGlobalNamespace()) { + return $type; + } + + return "{$this->namespace->getFullName()}\\{$type}"; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php new file mode 100644 index 0000000..a09656f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/DocLexer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +use PhpCsFixer\Preg; + +/** + * Copyright (c) 2006-2013 Doctrine Project. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocLexer +{ + public const T_NONE = 1; + public const T_INTEGER = 2; + public const T_STRING = 3; + public const T_FLOAT = 4; + + // All tokens that are also identifiers should be >= 100 + public const T_IDENTIFIER = 100; + public const T_AT = 101; + public const T_CLOSE_CURLY_BRACES = 102; + public const T_CLOSE_PARENTHESIS = 103; + public const T_COMMA = 104; + public const T_EQUALS = 105; + public const T_NAMESPACE_SEPARATOR = 107; + public const T_OPEN_CURLY_BRACES = 108; + public const T_OPEN_PARENTHESIS = 109; + public const T_COLON = 112; + public const T_MINUS = 113; + + private const CATCHABLE_PATTERNS = [ + '[a-z_\\\][a-z0-9_\:\\\]*[a-z_][a-z0-9_]*', + '(?:[+-]?[0-9]+(?:[\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?', + '"(?:""|[^"])*+"', + ]; + + private const NON_CATCHABLE_PATTERNS = ['\s+', '\*+', '(.)']; + + /** @var array */ + private array $noCase = [ + '@' => self::T_AT, + ',' => self::T_COMMA, + '(' => self::T_OPEN_PARENTHESIS, + ')' => self::T_CLOSE_PARENTHESIS, + '{' => self::T_OPEN_CURLY_BRACES, + '}' => self::T_CLOSE_CURLY_BRACES, + '=' => self::T_EQUALS, + ':' => self::T_COLON, + '-' => self::T_MINUS, + '\\' => self::T_NAMESPACE_SEPARATOR, + ]; + + /** @var list */ + private array $tokens = []; + + private int $position = 0; + + private int $peek = 0; + + private ?string $regex = null; + + public function setInput(string $input): void + { + $this->tokens = []; + $this->reset(); + $this->scan($input); + } + + public function reset(): void + { + $this->peek = 0; + $this->position = 0; + } + + public function peek(): ?Token + { + return $this->tokens[$this->position + $this->peek++] ?? null; + } + + /** + * @return self::T_* + */ + private function getType(string &$value): int + { + $type = self::T_NONE; + + if ('"' === $value[0]) { + $value = str_replace('""', '"', substr($value, 1, \strlen($value) - 2)); + + return self::T_STRING; + } + + if (isset($this->noCase[$value])) { + return $this->noCase[$value]; + } + + if ('_' === $value[0] || '\\' === $value[0] || !Preg::match('/[^A-Za-z]/', $value[0])) { + return self::T_IDENTIFIER; + } + + if (is_numeric($value)) { + return str_contains($value, '.') || str_contains(strtolower($value), 'e') + ? self::T_FLOAT : self::T_INTEGER; + } + + return $type; + } + + private function scan(string $input): void + { + $this->regex ??= \sprintf( + '/(%s)|%s/%s', + implode(')|(', self::CATCHABLE_PATTERNS), + implode('|', self::NON_CATCHABLE_PATTERNS), + 'iu', + ); + + $flags = \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_OFFSET_CAPTURE; + $matches = Preg::split($this->regex, $input, -1, $flags); + + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $firstMatch = $match[0]; + $type = $this->getType($firstMatch); + + $this->tokens[] = new Token($type, $firstMatch, (int) $match[1]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php new file mode 100644 index 0000000..b82097c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +/** + * A Doctrine annotation token. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Token +{ + private int $type; + + private string $content; + + private int $position; + + /** + * @param int $type The type + * @param string $content The content + */ + public function __construct(int $type = DocLexer::T_NONE, string $content = '', int $position = 0) + { + $this->type = $type; + $this->content = $content; + $this->position = $position; + } + + public function getType(): int + { + return $this->type; + } + + public function setType(int $type): void + { + $this->type = $type; + } + + public function getContent(): string + { + return $this->content; + } + + public function setContent(string $content): void + { + $this->content = $content; + } + + public function getPosition(): int + { + return $this->position; + } + + /** + * Returns whether the token type is one of the given types. + * + * @param int|list $types + */ + public function isType($types): bool + { + if (!\is_array($types)) { + $types = [$types]; + } + + return \in_array($this->getType(), $types, true); + } + + /** + * Overrides the content with an empty string. + */ + public function clear(): void + { + $this->setContent(''); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php new file mode 100644 index 0000000..7763a2d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php @@ -0,0 +1,298 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Doctrine\Annotation; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token as PhpToken; + +/** + * A list of Doctrine annotation tokens. + * + * @internal + * + * @extends \SplFixedArray + * + * `SplFixedArray` uses `T|null` in return types because value can be null if an offset is unset or if the size does not match the number of elements. + * But our class takes care of it and always ensures correct size and indexes, so that these methods never return `null` instead of `Token`. + * + * @method Token offsetGet($offset) + * @method \Traversable getIterator() + * @method array toArray() + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Tokens extends \SplFixedArray +{ + /** + * @param list $ignoredTags + * + * @throws \InvalidArgumentException + */ + public static function createFromDocComment(PhpToken $input, array $ignoredTags = []): self + { + if (!$input->isGivenKind(\T_DOC_COMMENT)) { + throw new \InvalidArgumentException('Input must be a T_DOC_COMMENT token.'); + } + + $tokens = []; + + $content = $input->getContent(); + $ignoredTextPosition = 0; + $currentPosition = 0; + $token = null; + while (false !== $nextAtPosition = strpos($content, '@', $currentPosition)) { + if (0 !== $nextAtPosition && !Preg::match('/\s/', $content[$nextAtPosition - 1])) { + $currentPosition = $nextAtPosition + 1; + + continue; + } + + $lexer = new DocLexer(); + $lexer->setInput(substr($content, $nextAtPosition)); + + $scannedTokens = []; + $index = 0; + $nbScannedTokensToUse = 0; + $nbScopes = 0; + while (null !== $token = $lexer->peek()) { + if (0 === $index && !$token->isType(DocLexer::T_AT)) { + break; + } + + if (1 === $index) { + if (!$token->isType(DocLexer::T_IDENTIFIER) || \in_array($token->getContent(), $ignoredTags, true)) { + break; + } + + $nbScannedTokensToUse = 2; + } + + if ($index >= 2 && 0 === $nbScopes && !$token->isType([DocLexer::T_NONE, DocLexer::T_OPEN_PARENTHESIS])) { + break; + } + + $scannedTokens[] = $token; + + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + ++$nbScopes; + } elseif ($token->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + if (0 === --$nbScopes) { + $nbScannedTokensToUse = \count($scannedTokens); + + break; + } + } + + ++$index; + } + + if (0 !== $nbScopes) { + break; + } + + if (0 !== $nbScannedTokensToUse) { + $ignoredTextLength = $nextAtPosition - $ignoredTextPosition; + if (0 !== $ignoredTextLength) { + $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition, $ignoredTextLength)); + } + + $lastTokenEndIndex = 0; + foreach (\array_slice($scannedTokens, 0, $nbScannedTokensToUse) as $scannedToken) { + $token = $scannedToken->isType(DocLexer::T_STRING) + ? new Token( + $scannedToken->getType(), + '"'.str_replace('"', '""', $scannedToken->getContent()).'"', + $scannedToken->getPosition(), + ) + : $scannedToken; + + $missingTextLength = $token->getPosition() - $lastTokenEndIndex; + if ($missingTextLength > 0) { + $tokens[] = new Token(DocLexer::T_NONE, substr( + $content, + $nextAtPosition + $lastTokenEndIndex, + $missingTextLength, + )); + } + + $tokens[] = new Token($token->getType(), $token->getContent()); + $lastTokenEndIndex = $token->getPosition() + \strlen($token->getContent()); + } + + $currentPosition = $ignoredTextPosition = $nextAtPosition + $token->getPosition() + \strlen($token->getContent()); + } else { + $currentPosition = $nextAtPosition + 1; + } + } + + if ($ignoredTextPosition < \strlen($content)) { + $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition)); + } + + return self::fromArray($tokens); + } + + /** + * Create token collection from array. + * + * @param array $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null): self + { + $tokens = new self(\count($array)); + + if (null === $saveIndices || $saveIndices) { + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + + return $tokens; + } + + /** + * Returns the index of the closest next token that is neither a comment nor a whitespace token. + */ + public function getNextMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + + /** + * Returns the index of the last token that is part of the annotation at the given index. + */ + public function getAnnotationEnd(int $index): ?int + { + $currentIndex = null; + + if (isset($this[$index + 2])) { + if ($this[$index + 2]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $currentIndex = $index + 2; + } elseif ( + isset($this[$index + 3]) + && $this[$index + 2]->isType(DocLexer::T_NONE) + && $this[$index + 3]->isType(DocLexer::T_OPEN_PARENTHESIS) + && Preg::match('/^(\R\s*\*\s*)*\s*$/', $this[$index + 2]->getContent()) + ) { + $currentIndex = $index + 3; + } + } + + if (null !== $currentIndex) { + $level = 0; + for ($max = \count($this); $currentIndex < $max; ++$currentIndex) { + if ($this[$currentIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + ++$level; + } elseif ($this[$currentIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + --$level; + } + + if (0 === $level) { + return $currentIndex; + } + } + + return null; + } + + return $index + 1; + } + + /** + * Returns the code from the tokens. + */ + public function getCode(): string + { + $code = ''; + foreach ($this as $token) { + $code .= $token->getContent(); + } + + return $code; + } + + /** + * Inserts a token at the given index. + */ + public function insertAt(int $index, Token $token): void + { + $this->setSize($this->getSize() + 1); + + for ($i = $this->getSize() - 1; $i > $index; --$i) { + $this[$i] = $this[$i - 1] ?? new Token(); + } + + $this[$index] = $token; + } + + /** + * @param null|int $index + * @param null|Token $token + */ + public function offsetSet($index, $token): void + { + if (!$token instanceof Token) { + throw new \InvalidArgumentException(\sprintf('Token must be an instance of %s, "%s" given.', Token::class, get_debug_type($token))); + } + + parent::offsetSet($index, $token); + } + + /** + * @param mixed $index + * + * @throws \OutOfBoundsException + */ + public function offsetUnset($index): void + { + if (!isset($this[$index])) { + throw new \OutOfBoundsException(\sprintf('Index "%s" is invalid or does not exist.', $index)); + } + + $max = \count($this) - 1; + while ($index < $max) { + $this[$index] = $this[$index + 1]; + ++$index; + } + + parent::offsetUnset($index); + + $this->setSize($max); + } + + private function getMeaningfulTokenSibling(int $index, int $direction): ?int + { + while (true) { + $index += $direction; + + if (!$this->offsetExists($index)) { + break; + } + + if (!$this[$index]->isType(DocLexer::T_NONE)) { + return $index; + } + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php new file mode 100644 index 0000000..6bc5fef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Utils; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocumentationLocator +{ + private string $path; + + public function __construct() + { + $this->path = \dirname(__DIR__, 2).'/doc'; + } + + public function getFixersDocumentationDirectoryPath(): string + { + return $this->path.'/rules'; + } + + public function getFixersDocumentationIndexFilePath(): string + { + return $this->getFixersDocumentationDirectoryPath().'/index.rst'; + } + + public function getFixerDocumentationFilePath(FixerInterface $fixer): string + { + return $this->getFixersDocumentationDirectoryPath().'/'.Preg::replaceCallback( + '/^.*\\\(.+)\\\(.+)Fixer$/', + static fn (array $matches): string => Utils::camelCaseToUnderscore($matches[1]).'/'.Utils::camelCaseToUnderscore($matches[2]), + \get_class($fixer), + ).'.rst'; + } + + public function getFixerDocumentationFileRelativePath(FixerInterface $fixer): string + { + return Preg::replace( + '#^'.preg_quote($this->getFixersDocumentationDirectoryPath(), '#').'/#', + '', + $this->getFixerDocumentationFilePath($fixer), + ); + } + + public function getRuleSetsDocumentationDirectoryPath(): string + { + return $this->path.'/ruleSets'; + } + + public function getRuleSetsDocumentationIndexFilePath(): string + { + return $this->getRuleSetsDocumentationDirectoryPath().'/index.rst'; + } + + public function getRuleSetsDocumentationFilePath(string $name): string + { + return $this->getRuleSetsDocumentationDirectoryPath().'/'.str_replace(':risky', 'Risky', ucfirst(substr($name, 1))).'.rst'; + } + + public function getUsageFilePath(): string + { + return $this->path.'/usage.rst'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTag.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTag.php new file mode 100644 index 0000000..7e93eea --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTag.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocumentationTag +{ + /** + * @var DocumentationTagType::* + * + * @readonly + */ + public string $type; + + /** + * @readonly + */ + public string $title; + + /** + * @readonly + */ + public ?string $description; + + /** + * @param DocumentationTagType::* $type + */ + public function __construct( + string $type, + string $title, + ?string $description = null + ) { + $this->type = $type; + $this->title = $title; + $this->description = $description; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagGenerator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagGenerator.php new file mode 100644 index 0000000..d79f598 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagGenerator.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\InternalFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionInterface; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\InternalRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\Utils; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocumentationTagGenerator +{ + /** + * @return list + */ + public static function analyseRuleSet(RuleSetDefinitionInterface $ruleSetDefinition): array + { + $tags = []; + + // not possible for set to be DocumentationTagType::EXPERIMENTAL + + if ($ruleSetDefinition instanceof InternalRuleSetDefinitionInterface) { + $tags[] = new DocumentationTag( + DocumentationTagType::INTERNAL, + 'This rule set is INTERNAL', + 'Set is expected to be used only on PHP CS Fixer project itself.', + ); + } + + if ($ruleSetDefinition instanceof DeprecatedRuleSetDefinitionInterface) { + $alternatives = $ruleSetDefinition->getSuccessorsNames(); + + $tags[] = new DocumentationTag( + DocumentationTagType::DEPRECATED, + \sprintf('This rule set is DEPRECATED and will be removed in the next major version %d.0', Application::getMajorVersion() + 1), + 0 !== \count($alternatives) + ? \sprintf( + 'You should use %s instead.', + Utils::naturalLanguageJoinWithBackticks($alternatives), + ) + : 'No replacement available.', + ); + } + + if ($ruleSetDefinition->isRisky()) { + $tags[] = new DocumentationTag( + DocumentationTagType::RISKY, + 'This rule set is RISKY', + 'This set contains rules that are risky. Using it may lead to changes in your code\'s logic and behaviour. Use it with caution and review changes before incorporating them into your code base.', + ); + } + + // not possible for set to be DocumentationTagType::CONFIGURABLE + + if ($ruleSetDefinition instanceof AutomaticRuleSetDefinitionInterface) { + $tags[] = new DocumentationTag( + DocumentationTagType::AUTOMATIC, + 'This rule set is AUTOMATIC', + '⚡ '.strip_tags(AutomaticRuleSetDefinitionInterface::WARNING_MESSAGE_DECORATED), + ); + } + + return $tags; + } + + /** + * @return list + */ + public static function analyseRule(FixerInterface $fixer): array + { + $tags = []; + + if ($fixer instanceof ExperimentalFixerInterface) { + $tags[] = new DocumentationTag( + DocumentationTagType::EXPERIMENTAL, + 'This rule is EXPERIMENTAL', + 'Rule is not covered with backward compatibility promise and may produce unstable or unexpected results, use it at your own risk. Rule\'s behaviour may be changed at any point, including rule\'s name; its options\' names, availability and allowed values; its default configuration. Rule may be even removed without prior notice. Feel free to provide feedback and help with determining final state of the rule.', + ); + } + + if ($fixer instanceof InternalFixerInterface) { + $tags[] = new DocumentationTag( + DocumentationTagType::INTERNAL, + 'This rule is INTERNAL', + 'Rule is expected to be used only on PHP CS Fixer project itself.', + ); + } + + if ($fixer instanceof DeprecatedFixerInterface) { + $alternatives = $fixer->getSuccessorsNames(); + + $tags[] = new DocumentationTag( + DocumentationTagType::DEPRECATED, + \sprintf('This rule is DEPRECATED and will be removed in the next major version %d.0', Application::getMajorVersion() + 1), + 0 !== \count($alternatives) + ? \sprintf( + 'You should use %s instead.', + Utils::naturalLanguageJoinWithBackticks($alternatives), + ) + : 'No replacement available.', + ); + } + + if ($fixer->isRisky()) { + $riskyDescription = $fixer->getDefinition()->getRiskyDescription(); + + $tags[] = new DocumentationTag( + DocumentationTagType::RISKY, + 'This rule is RISKY', + // @TODO - FRS enable me + // 'Using it may lead to changes in your code\'s logic and behaviour. Use it with caution and review changes before incorporating them into your code base.' + // \n\n + '' + .(null !== $riskyDescription ? "{$riskyDescription}" : ''), + ); + } + + if ($fixer instanceof ConfigurableFixerInterface) { + $options = array_map( + static fn (FixerOptionInterface $option): string => '`'.$option->getName().'`', + $fixer->getConfigurationDefinition()->getOptions(), + ); + $tags[] = new DocumentationTag( + DocumentationTagType::CONFIGURABLE, + 'This rule is CONFIGURABLE', + \sprintf( + 'You can configure this rule using the following option%s: %s.', + 1 === \count($options) ? '' : 's', + implode(', ', $options), + ), + ); + } + + // not possible for set to be DocumentationTagType::AUTOMATIC + + return $tags; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagType.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagType.php new file mode 100644 index 0000000..6b11da2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationTagType.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DocumentationTagType +{ + public const EXPERIMENTAL = 'experimental'; + public const INTERNAL = 'internal'; + public const DEPRECATED = 'deprecated'; + public const RISKY = 'risky'; + public const CONFIGURABLE = 'configurable'; + public const AUTOMATIC = 'automatic'; + + private function __construct() {} +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php new file mode 100644 index 0000000..fee428d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php @@ -0,0 +1,440 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerConfiguration\AliasedFixerOption; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionInterface; +use PhpCsFixer\FixerDefinition\CodeSampleInterface; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerDocumentGenerator +{ + private DocumentationLocator $locator; + + private FullDiffer $differ; + + /** @var array */ + private array $ruleSetDefinitions; + + public function __construct(DocumentationLocator $locator) + { + $this->locator = $locator; + $this->differ = new FullDiffer(); + $this->ruleSetDefinitions = RuleSets::getSetDefinitions(); + } + + public function generateFixerDocumentation(FixerInterface $fixer): string + { + $name = $fixer->getName(); + $title = "Rule ``{$name}``"; + $titleLine = str_repeat('=', \strlen($title)); + $doc = "{$titleLine}\n{$title}\n{$titleLine}"; + + $definition = $fixer->getDefinition(); + $doc .= "\n\n".RstUtils::toRst($definition->getSummary()); + + $description = $definition->getDescription(); + + if (null !== $description) { + $description = RstUtils::toRst($description); + $doc .= <<title)); + + return \sprintf( + "\n%s\n%s\n\n%s", + $tag->title, + $titleLine, + null === $tag->description ? '' : RstUtils::toRst($tag->description, 0), + ); + }, + $tags, + ); + + if ([] !== $warnings) { + $warningsHeader = 1 === \count($warnings) ? 'Warning' : 'Warnings'; + + $doc .= "\n\n".$header($warningsHeader).implode("\n", $warnings); + } + + if ($fixer instanceof ConfigurableFixerInterface) { + $fixerInFutureMode = self::createFixerInFutureMode($fixer); + + $doc .= <<<'RST' + + + Configuration + ------------- + RST; + + $configurationDefinition = $fixer->getConfigurationDefinition(); + + foreach ($configurationDefinition->getOptions() as $option) { + $optionInfo = "``{$option->getName()}``"; + $optionInfo .= "\n".str_repeat('~', \strlen($optionInfo)); + + if ($option instanceof DeprecatedFixerOptionInterface) { + $deprecationMessage = RstUtils::toRst($option->getDeprecationMessage()); + $optionInfo .= "\n\n.. warning:: This option is deprecated and will be removed in the next major version. {$deprecationMessage}"; + } + + $optionInfo .= "\n\n".RstUtils::toRst($option->getDescription()); + + if ($option instanceof AliasedFixerOption) { + $optionInfo .= "\n\n.. note:: The previous name of this option was ``{$option->getAlias()}`` but it is now deprecated and will be removed in the next major version."; + } + + $allowed = HelpCommand::getDisplayableAllowedValues($option); + + if (null === $allowed) { + $allowedKind = 'Allowed types'; + $allowedTypes = $option->getAllowedTypes(); + if (null !== $allowedTypes) { + $allowed = array_map( + static fn (string $value): string => '``'.Utils::convertArrayTypeToList($value).'``', + $allowedTypes, + ); + } + } else { + $allowedKind = 'Allowed values'; + $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset + ? 'a subset of ``'.Utils::toString($value->getAllowedValues()).'``' + : '``'.Utils::toString($value).'``', $allowed); + } + + if (null !== $allowed) { + $allowed = Utils::naturalLanguageJoin($allowed, ''); + $optionInfo .= "\n\n{$allowedKind}: {$allowed}"; + } + + if ($option->hasDefault()) { + $optionInfo .= \sprintf("\n\nDefault value: ``%s``", Utils::toString($option->getDefault())); + + $optionInFutureMode = array_find( + $fixerInFutureMode->getConfigurationDefinition()->getOptions(), + static fn (FixerOptionInterface $opt): bool => $option->getName() === $opt->getName(), + ); + \assert(null !== $optionInFutureMode); // if rule exist in v3, shall exist in future mode too, as it does not remove options + if ($optionInFutureMode->getDefault() !== $option->getDefault()) { + $optionInfo .= \sprintf("\n\nDefault value (future-mode): ``%s``", Utils::toString($optionInFutureMode->getDefault())); + } + } else { + $optionInfo .= "\n\nThis option is required."; + } + + $doc .= "\n\n{$optionInfo}"; + } + } + + $samples = $definition->getCodeSamples(); + + if (0 !== \count($samples)) { + $doc .= <<<'RST' + + + Examples + -------- + RST; + + foreach ($samples as $index => $sample) { + $title = \sprintf('Example #%d', $index + 1); + $titleLine = str_repeat('~', \strlen($title)); + $doc .= "\n\n{$title}\n{$titleLine}"; + + if ($fixer instanceof ConfigurableFixerInterface) { + if (null === $sample->getConfiguration()) { + $doc .= "\n\n*Default* configuration."; + } else { + $doc .= \sprintf( + "\n\nWith configuration: ``%s``.", + Utils::toString($sample->getConfiguration()), + ); + } + } + + $doc .= "\n".$this->generateSampleDiff($fixer, $sample, $index + 1, $name); + } + } + + $ruleSetConfigs = self::getSetsOfRule($name); + + if ([] !== $ruleSetConfigs) { + $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; + $doc .= << $config) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($set); + \assert(false !== strrpos($ruleSetPath, '/')); + $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); + + \assert(isset($this->ruleSetDefinitions[$set])); + $ruleSetDefinition = $this->ruleSetDefinitions[$set]; + + if ($ruleSetDefinition instanceof AutomaticRuleSetDefinitionInterface) { + continue; + } + + $deprecatedDesc = ($ruleSetDefinition instanceof DeprecatedRuleSetDefinitionInterface) ? ' *(deprecated)*' : ''; + + $configInfo = (null !== $config) + ? " with config:\n\n ``".Utils::toString($config)."``\n" + : ''; + + $doc .= <<`_{$deprecatedDesc}{$configInfo}\n + RST; + } + + $doc = trim($doc); + } + + $reflectionObject = new \ReflectionObject($fixer); + $className = str_replace('\\', '\\\\', $reflectionObject->getName()); + $fileName = $reflectionObject->getFileName(); + \assert(false !== $fileName); + $fileName = str_replace('\\', '/', $fileName); + $fileName = substr($fileName, (int) strrpos($fileName, '/src/Fixer/') + 1); + $fileName = "`{$className} <./../../../{$fileName}>`_"; + + $testFileName = Preg::replace('~.*\K/src/(?=Fixer/)~', '/tests/', $fileName); + $testFileName = Preg::replace('~PhpCsFixer\\\\\\\\\K(?=Fixer\\\\\\\)~', 'Tests\\\\\\\\', $testFileName); + $testFileName = Preg::replace('~(?= <|\.php>)~', 'Test', $testFileName); + + $doc .= <<', $doc); + + return "{$doc}\n"; + } + + /** + * @internal + * + * @return array> + */ + public static function getSetsOfRule(string $ruleName): array + { + static $ruleSetCache = null; + + if (null === $ruleSetCache) { + $definitionNames = array_keys( + array_filter( + RuleSets::getSetDefinitions(), + static fn (RuleSetDefinitionInterface $definition): bool => !$definition instanceof AutomaticRuleSetDefinitionInterface, + ), + ); + $ruleSetCache = array_combine( + $definitionNames, + array_map( + static fn (string $name): RuleSet => new RuleSet([$name => true]), + $definitionNames, + ), + ); + } + + $ruleSetConfigs = []; + + foreach ($ruleSetCache as $set => $ruleSet) { + if ($ruleSet->hasRule($ruleName)) { + $ruleSetConfigs[$set] = $ruleSet->getRuleConfiguration($ruleName); + } + } + + return $ruleSetConfigs; + } + + /** + * @param list $fixers + */ + public function generateFixersDocumentationIndex(array $fixers): string + { + $overrideGroups = [ + 'PhpUnit' => 'PHPUnit', + 'PhpTag' => 'PHP Tag', + 'Phpdoc' => 'PHPDoc', + ]; + + usort($fixers, static fn (FixerInterface $a, FixerInterface $b): int => \get_class($a) <=> \get_class($b)); + + $documentation = <<<'RST' + ======================= + List of Available Rules + ======================= + RST; + + $currentGroup = null; + + foreach ($fixers as $fixer) { + $namespace = Preg::replace('/^.*\\\(.+)\\\.+Fixer$/', '$1', \get_class($fixer)); + $group = $overrideGroups[$namespace] ?? Preg::replace('/(?<=[[:lower:]])(?=[[:upper:]])/', ' ', $namespace); + + if ($group !== $currentGroup) { + $underline = str_repeat('-', \strlen($group)); + $documentation .= "\n\n{$group}\n{$underline}\n"; + + $currentGroup = $group; + } + + $path = './'.$this->locator->getFixerDocumentationFileRelativePath($fixer); + + $tags = array_map( + static fn (DocumentationTag $tag): string => $tag->type, + DocumentationTagGenerator::analyseRule($fixer), + ); + + $attributes = 0 === \count($tags) + ? '' + : ' *('.implode(', ', $tags).')*'; + + $summary = str_replace('`', '``', $fixer->getDefinition()->getSummary()); + + $documentation .= <<getName()} <{$path}>`_{$attributes} + + {$summary} + RST; + } + + return "{$documentation}\n"; + } + + /** + * @template T of FixerInterface + * + * @param T $fixer + * + * @return T + */ + private static function createFixerInFutureMode(FixerInterface $fixer): FixerInterface + { + $object = Future::runWithEnforcedFutureMode( + static fn () => (new \ReflectionObject($fixer))->newInstance(), + ); + + \assert($object instanceof $fixer); + + return $object; + } + + private function generateSampleDiff(FixerInterface $fixer, CodeSampleInterface $sample, int $sampleNumber, string $ruleName): string + { + if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) { + $existingFile = @file_get_contents($this->locator->getFixerDocumentationFilePath($fixer)); + + if (false !== $existingFile) { + Preg::match("/\\RExample #{$sampleNumber}\\R.+?(?\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|$)/s", $existingFile, $matches); + + if (isset($matches['diff'])) { + return $matches['diff']; + } + } + + $error = <<getCode(); + + $tokens = Tokens::fromCode($old); + $file = $sample instanceof FileSpecificCodeSampleInterface + ? $sample->getSplFileInfo() + : new StdinFileInfo(); + + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($sample->getConfiguration() ?? []); + } + + $fixer->fix($file, $tokens); + + $diff = $this->differ->diff($old, $tokens->generateCode()); + $diff = Preg::replace('/@@[ \+\-\d,]+@@\n/', '', $diff); + $diff = Preg::replace('/\r/', '^M', $diff); + $diff = Preg::replace('/^ $/m', '', $diff); + $diff = Preg::replace('/\n$/', '', $diff); + $diff = RstUtils::indent($diff, 3); + + return << + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Preg; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RstUtils +{ + private function __construct() + { + // cannot create instance of util. class + } + + public static function toRst(string $string, int $indent = 0): string + { + $string = wordwrap(self::ensureProperInlineCode($string), 80 - $indent); + + return 0 === $indent ? $string : self::indent($string, $indent); + } + + public static function ensureProperInlineCode(string $string): string + { + return Preg::replace('/(? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\Utils; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RuleSetDocumentationGenerator +{ + private DocumentationLocator $locator; + + public function __construct(DocumentationLocator $locator) + { + $this->locator = $locator; + } + + /** + * @param list $fixers + */ + public function generateRuleSetsDocumentation(RuleSetDefinitionInterface $definition, array $fixers): string + { + $fixerNames = []; + + foreach ($fixers as $fixer) { + $fixerNames[$fixer->getName()] = $fixer; + } + + $title = "Rule set ``{$definition->getName()}``"; + $titleLine = str_repeat('=', \strlen($title)); + $doc = "{$titleLine}\n{$title}\n{$titleLine}\n\n".$definition->getDescription(); + + $header = static function (string $message, string $underline = '-'): string { + $line = str_repeat($underline, \strlen($message)); + + return "{$message}\n{$line}\n"; + }; + + $tags = DocumentationTagGenerator::analyseRuleSet($definition); + $warnings = array_map( + static function (DocumentationTag $tag): string { + $titleLine = str_repeat('~', \strlen($tag->title)); + + return \sprintf( + "\n%s\n%s\n\n%s", + $tag->title, + $titleLine, + null === $tag->description ? '' : RstUtils::toRst($tag->description, 0), + ); + }, + $tags, + ); + + if ([] !== $warnings) { + $warningsHeader = 1 === \count($warnings) ? 'Warning' : 'Warnings'; + + $doc .= "\n\n".$header($warningsHeader).implode("\n", $warnings); + } + + $rules = $definition instanceof AutomaticRuleSetDefinitionInterface + ? $definition->getRulesCandidates() + : $definition->getRules(); + + if ([] === $rules) { + $doc .= "\n\nThis is an empty set."; + } else { + $enabledRules = array_filter($rules, static fn ($config) => false !== $config); + $disabledRules = array_filter($rules, static fn ($config) => false === $config); + + $listRules = function (array $rules) use (&$doc, $fixerNames): void { + foreach ($rules as $rule => $config) { + if (str_starts_with($rule, '@')) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($rule); + \assert(false !== strrpos($ruleSetPath, '/')); + $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); + + $doc .= "\n- `{$rule} <.{$ruleSetPath}>`_"; + } else { + \assert(isset($fixerNames[$rule])); + $path = Preg::replace( + '#^'.preg_quote($this->locator->getFixersDocumentationDirectoryPath(), '#').'/#', + './../rules/', + $this->locator->getFixerDocumentationFilePath($fixerNames[$rule]), + ); + + $doc .= "\n- `{$rule} <{$path}>`_"; + } + + if (!\is_bool($config)) { + $doc .= " with config:\n\n ``".Utils::toString($config)."``\n"; + } + } + }; + + $rulesCandidatesDescriptionHeader = $definition instanceof AutomaticRuleSetDefinitionInterface + ? ' candidates' + : ''; + + if ([] !== $enabledRules) { + $doc .= "\n\n".$header("Rules{$rulesCandidatesDescriptionHeader}"); + $listRules($enabledRules); + } + + if ([] !== $disabledRules) { + $doc .= "\n\n".$header("Disabled rules{$rulesCandidatesDescriptionHeader}"); + + $listRules($disabledRules); + } + } + + return $doc."\n"; + } + + /** + * @param array $setDefinitions + */ + public function generateRuleSetsDocumentationIndex(array $setDefinitions): string + { + $documentation = <<<'RST' + =========================== + List of Available Rule sets + =========================== + RST; + + foreach ($setDefinitions as $path => $definition) { + \assert(false !== strrpos($path, '/')); + $path = substr($path, strrpos($path, '/')); + + $attributes = []; + + if ($definition instanceof DeprecatedRuleSetDefinitionInterface) { + $attributes[] = 'deprecated'; + } + + $attributes = 0 === \count($attributes) + ? '' + : ' *('.implode(', ', $attributes).')*'; + + $documentation .= "\n- `{$definition->getName()} <.{$path}>`_{$attributes}"; + } + + return $documentation."\n"; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php new file mode 100644 index 0000000..1b1cfe8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Error; + +/** + * An abstraction for errors that can occur before and during fixing. + * + * @author Andreas Möller + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Error implements \JsonSerializable +{ + /** + * Error which has occurred in linting phase, before applying any fixers. + */ + public const TYPE_INVALID = 1; + + /** + * Error which has occurred during fixing phase. + */ + public const TYPE_EXCEPTION = 2; + + /** + * Error which has occurred in linting phase, after applying any fixers. + */ + public const TYPE_LINT = 3; + + /** @var self::TYPE_* */ + private int $type; + + private string $filePath; + + private ?\Throwable $source; + + /** + * @var list + */ + private array $appliedFixers; + + private string $diff; + + /** + * @param self::TYPE_* $type + * @param list $appliedFixers + */ + public function __construct(int $type, string $filePath, ?\Throwable $source = null, array $appliedFixers = [], string $diff = '') + { + $this->type = $type; + $this->filePath = $filePath; + $this->source = $source; + $this->appliedFixers = $appliedFixers; + $this->diff = $diff; + } + + public function getFilePath(): string + { + return $this->filePath; + } + + public function getSource(): ?\Throwable + { + return $this->source; + } + + public function getType(): int + { + return $this->type; + } + + /** + * @return list + */ + public function getAppliedFixers(): array + { + return $this->appliedFixers; + } + + public function getDiff(): string + { + return $this->diff; + } + + /** + * @return array{ + * type: self::TYPE_*, + * filePath: string, + * source: null|array{class: class-string, message: string, code: int, file: string, line: int}, + * appliedFixers: list, + * diff: null|string + * } + */ + public function jsonSerialize(): array + { + return [ + 'type' => $this->type, + 'filePath' => $this->filePath, + 'source' => null !== $this->source + ? [ + 'class' => \get_class($this->source), + 'message' => $this->source->getMessage(), + 'code' => $this->source->getCode(), + 'file' => $this->source->getFile(), + 'line' => $this->source->getLine(), + ] + : null, + 'appliedFixers' => $this->appliedFixers, + 'diff' => $this->diff, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php new file mode 100644 index 0000000..a026c03 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Error; + +/** + * Manager of errors that occur during fixing. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ErrorsManager +{ + /** + * @var list + */ + private array $errors = []; + + /** + * Returns errors reported during linting before fixing. + * + * @return list + */ + public function getInvalidErrors(): array + { + return array_values(array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_INVALID === $error->getType())); + } + + /** + * Returns errors reported during fixing. + * + * @return list + */ + public function getExceptionErrors(): array + { + return array_values(array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_EXCEPTION === $error->getType())); + } + + /** + * Returns errors reported during linting after fixing. + * + * @return list + */ + public function getLintErrors(): array + { + return array_values(array_filter($this->errors, static fn (Error $error): bool => Error::TYPE_LINT === $error->getType())); + } + + /** + * @return list + */ + public function getAllErrors(): array + { + return $this->errors; + } + + /** + * Returns errors reported for specified path. + * + * @return list + */ + public function forPath(string $path): array + { + return array_values(array_filter($this->errors, static fn (Error $error): bool => $path === $error->getFilePath())); + } + + /** + * Returns true if no errors were reported. + */ + public function isEmpty(): bool + { + return [] === $this->errors; + } + + public function report(Error $error): void + { + $this->errors[] = $error; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/SourceExceptionFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/SourceExceptionFactory.php new file mode 100644 index 0000000..02d6d0e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Error/SourceExceptionFactory.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Error; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SourceExceptionFactory +{ + /** + * @param array{class: class-string<\Throwable>, message: string, code: int, file: string, line: int} $error + */ + public static function fromArray(array $error): \Throwable + { + $exceptionClass = $error['class']; + + try { + $exception = new $exceptionClass($error['message'], $error['code']); + + if ( + $exception->getMessage() !== $error['message'] + || $exception->getCode() !== $error['code'] + ) { + throw new \RuntimeException('Failed to create exception from array. Message and code are not the same.'); + } + } catch (\Throwable $e) { + $exception = new \RuntimeException( + \sprintf('[%s] %s', $exceptionClass, $error['message']), + $error['code'], + ); + } + + try { + $exceptionReflection = new \ReflectionClass($exception); + foreach (['file', 'line'] as $property) { + $propertyReflection = $exceptionReflection->getProperty($property); + + if (\PHP_VERSION_ID < 8_01_00) { + $propertyReflection->setAccessible(true); // @phpstan-ignore method.deprecated + } + + $propertyReflection->setValue($exception, $error[$property]); + + if (\PHP_VERSION_ID < 8_01_00) { + $propertyReflection->setAccessible(false); // @phpstan-ignore method.deprecated + } + } + } catch (\Throwable $reflectionException) { + // Ignore if we were not able to set file/line properties. In most cases it should be fine, + // we just need to make sure nothing is broken when we recreate errors from raw data passed from worker. + } + + return $exception; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandler.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandler.php new file mode 100644 index 0000000..840ab0a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandler.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ExecutorWithoutErrorHandler +{ + private function __construct() {} + + /** + * @template T + * + * @param callable(): T $callback + * + * @return T + * + * @throws ExecutorWithoutErrorHandlerException + */ + public static function execute(callable $callback) + { + /** @var ?string */ + $error = null; + + set_error_handler(static function (int $errorNumber, string $errorString, string $errorFile, int $errorLine) use (&$error): bool { + $error = $errorString; + + return true; + }); + + try { + $result = $callback(); + } finally { + restore_error_handler(); + } + + if (null !== $error) { + throw new ExecutorWithoutErrorHandlerException($error); + } + + return $result; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandlerException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandlerException.php new file mode 100644 index 0000000..371f7e6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ExecutorWithoutErrorHandlerException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ExecutorWithoutErrorHandlerException extends \RuntimeException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileReader.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileReader.php new file mode 100644 index 0000000..8f15293 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileReader.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * File reader that unify access to regular file and stdin-alike file. + * + * Regular file could be read multiple times with `file_get_contents`, but file provided on stdin cannot. + * Consecutive try will provide empty content for stdin-alike file. + * This reader unifies access to them. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileReader +{ + private ?string $stdinContent = null; + + public static function createSingleton(): self + { + static $instance = null; + + if (!$instance) { + $instance = new self(); + } + + return $instance; + } + + public function read(string $filePath): string + { + if ('php://stdin' === $filePath) { + if (null === $this->stdinContent) { + $this->stdinContent = $this->readRaw($filePath); + } + + return $this->stdinContent; + } + + return $this->readRaw($filePath); + } + + private function readRaw(string $realPath): string + { + $content = @file_get_contents($realPath); + + if (false === $content) { + $error = error_get_last(); + + throw new \RuntimeException(\sprintf( + 'Failed to read content from "%s".%s', + $realPath, + null !== $error ? ' '.$error['message'] : '', + )); + } + + return $content; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php new file mode 100644 index 0000000..a01c7a5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * Handles files removal with possibility to remove them on shutdown. + * + * @author Adam Klvač + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileRemoval +{ + /** + * List of observed files to be removed. + * + * @var array + */ + private array $files = []; + + public function __construct() + { + register_shutdown_function([$this, 'clean']); + } + + public function __destruct() + { + $this->clean(); + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __serialize(): array + { + throw new \BadMethodCallException('Cannot serialize '.self::class); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @param array $data + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __unserialize(array $data): void + { + throw new \BadMethodCallException('Cannot unserialize '.self::class); + } + + /** + * Adds a file to be removed. + */ + public function observe(string $path): void + { + $this->files[$path] = true; + } + + /** + * Removes a file from shutdown removal. + */ + public function delete(string $path): void + { + if (isset($this->files[$path])) { + unset($this->files[$path]); + } + + $this->unlink($path); + } + + /** + * Removes attached files. + */ + public function clean(): void + { + foreach ($this->files as $file => $value) { + $this->unlink($file); + } + + $this->files = []; + } + + private function unlink(string $path): void + { + @unlink($path); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Finder.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Finder.php new file mode 100644 index 0000000..e174ca7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Finder.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use Symfony\Component\Finder\Finder as BaseFinder; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @api-extendable + */ +class Finder extends BaseFinder +{ + public function __construct() + { + parent::__construct(); + + $this + ->files() + ->name('/\.php$/') + ->exclude('vendor') + ->ignoreDotFiles(Future::getV4OrV3(false, true)) + ->ignoreVCS(true) // explicitly configure to not rely on Symfony default + ; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php new file mode 100644 index 0000000..ab4f348 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractIncrementOperatorFixer extends AbstractFixer +{ + final protected function findStart(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + $token = $tokens[$index]; + + $blockType = Tokens::detectBlockType($token); + if (null !== $blockType && !$blockType['isStart']) { + $index = $tokens->findBlockStart($blockType['type'], $index); + $token = $tokens[$index]; + } + } while (!$token->equalsAny(['$', [\T_VARIABLE]])); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->equals('$')) { + return $this->findStart($tokens, $index); + } + + if ($prevToken->isObjectOperator()) { + return $this->findStart($tokens, $prevIndex); + } + + if ($prevToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$prevPrevIndex]->isGivenKind([\T_STATIC, \T_STRING])) { + return $this->findStart($tokens, $prevIndex); + } + + $index = $tokens->getTokenNotOfKindsSibling($prevIndex, -1, [\T_NS_SEPARATOR, \T_STATIC, \T_STRING]); + $index = $tokens->getNextMeaningfulToken($index); + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php new file mode 100644 index 0000000..a57e978 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\PhpUnitTestCaseAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractPhpUnitFixer extends AbstractFixer +{ + use DocBlockAnnotationTrait; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_STRING]); + } + + final protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ((new PhpUnitTestCaseAnalyzer())->findPhpUnitClasses($tokens) as $indices) { + $this->applyPhpUnitClassFix($tokens, $indices[0], $indices[1]); + } + } + + abstract protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void; + + /** + * @return iterable + */ + protected function getPreviousAssertCall(Tokens $tokens, int $startIndex, int $endIndex): iterable + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $endIndex; $index > $startIndex; --$index) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_STRING]]); + + // test if "assert" something call + $loweredContent = strtolower($tokens[$index]->getContent()); + + if (!str_starts_with($loweredContent, 'assert')) { + continue; + } + + // test candidate for simple calls like: ([\]+'some fixable call'(...)) + $openBraceIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$openBraceIndex]->equals('(')) { + continue; + } + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $index)) { + continue; + } + + yield [ + 'index' => $index, + 'loweredName' => $loweredContent, + 'openBraceIndex' => $openBraceIndex, + 'closeBraceIndex' => $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openBraceIndex), + ]; + } + } + + final protected function isTestAttributePresent(Tokens $tokens, int $index): bool + { + $attributeIndex = $tokens->getPrevTokenOfKind($index, ['{', [FCT::T_ATTRIBUTE]]); + if (!$tokens[$attributeIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { + return false; + } + + $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); + + foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) { + foreach ($attributeAnalysis->getAttributes() as $attribute) { + $attributeName = strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)); + if ('phpunit\framework\attributes\test' === $attributeName) { + return true; + } + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php new file mode 100644 index 0000000..cba2262 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractShortOperatorFixer.php @@ -0,0 +1,265 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractShortOperatorFixer extends AbstractFixer +{ + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 3; --$index) { + if (!$this->isOperatorTokenCandidate($tokens, $index)) { + continue; + } + + // get what is before the operator + + $beforeRange = $this->getBeforeOperatorRange($tokens, $index); + $equalsIndex = $tokens->getPrevMeaningfulToken($beforeRange['start']); + + // make sure that before that is '=' + + if (!$tokens[$equalsIndex]->equals('=')) { + continue; + } + + // get and check what is before '=' + + $assignRange = $this->getBeforeOperatorRange($tokens, $equalsIndex); + $beforeAssignmentIndex = $tokens->getPrevMeaningfulToken($assignRange['start']); + + if ($tokens[$beforeAssignmentIndex]->equals(':')) { + if (!$this->belongsToSwitchOrAlternativeSyntax($alternativeSyntaxAnalyzer, $tokens, $beforeAssignmentIndex)) { + continue; + } + } elseif (!$tokens[$beforeAssignmentIndex]->equalsAny([';', '{', '}', '(', ')', ',', [\T_OPEN_TAG], [\T_RETURN]])) { + continue; + } + + // check if "assign" and "before" the operator are (functionally) the same + + if (RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $beforeRange)) { + $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $beforeRange); + + continue; + } + + if (!$this->isOperatorCommutative($tokens[$index])) { + continue; + } + + $afterRange = $this->getAfterOperatorRange($tokens, $index); + + // check if "assign" and "after" the operator are (functionally) the same + if (!RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $afterRange)) { + continue; + } + + $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $afterRange); + } + } + + abstract protected function getReplacementToken(Token $token): Token; + + abstract protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool; + + /** + * @param array{start: int, end: int} $assignRange + * @param array{start: int, end: int} $operatorRange + */ + private function shortenOperation( + Tokens $tokens, + int $equalsIndex, + int $operatorIndex, + array $assignRange, + array $operatorRange + ): void { + $tokens[$equalsIndex] = $this->getReplacementToken($tokens[$operatorIndex]); + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndex); + $this->clearMeaningfulFromRange($tokens, $operatorRange); + + foreach ([$equalsIndex, $assignRange['end']] as $i) { + $i = $tokens->getNonEmptySibling($i, 1); + + if ($tokens[$i]->isWhitespace(" \t")) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } elseif (!$tokens[$i]->isWhitespace()) { + $tokens->insertAt($i, new Token([\T_WHITESPACE, ' '])); + } + } + } + + /** + * @return array{start: int, end: int} + */ + private function getAfterOperatorRange(Tokens $tokens, int $index): array + { + $index = $tokens->getNextMeaningfulToken($index); + $range = ['start' => $index]; + + while (true) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex || $tokens[$nextIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]])) { + break; + } + + $blockType = Tokens::detectBlockType($tokens[$nextIndex]); + + if (null === $blockType) { + $index = $nextIndex; + + continue; + } + + if (false === $blockType['isStart']) { + break; + } + + $index = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $range['end'] = $index; + + return $range; + } + + /** + * @return array{start: int, end: int} + */ + private function getBeforeOperatorRange(Tokens $tokens, int $index): array + { + static $blockOpenTypes; + + if (null === $blockOpenTypes) { + $blockOpenTypes = [',']; // not a true "block type", but speeds up things + + foreach (Tokens::getBlockEdgeDefinitions() as $definition) { + $blockOpenTypes[] = $definition['start']; + } + } + + $controlStructureWithoutBracesTypes = [\T_IF, \T_ELSE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE]; + + $previousIndex = $tokens->getPrevMeaningfulToken($index); + $previousToken = $tokens[$previousIndex]; + + if ($tokens[$previousIndex]->equalsAny($blockOpenTypes)) { + return ['start' => $index, 'end' => $index]; + } + + $range = ['end' => $previousIndex]; + $index = $previousIndex; + + while ($previousToken->equalsAny([ + '$', + ']', + ')', + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [\T_NS_SEPARATOR], + [\T_STRING], + [\T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($previousToken); + + if (null !== $blockType) { + $blockStart = $tokens->findBlockStart($blockType['type'], $previousIndex); + + if ($tokens[$previousIndex]->equals(')') && $tokens[$tokens->getPrevMeaningfulToken($blockStart)]->isGivenKind($controlStructureWithoutBracesTypes)) { + break; // we went too far back + } + + $previousIndex = $blockStart; + } + + $index = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + $previousToken = $tokens[$previousIndex]; + } + + if ($previousToken->isGivenKind(\T_OBJECT_OPERATOR)) { + $index = $this->getBeforeOperatorRange($tokens, $previousIndex)['start']; + } elseif ($previousToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + $index = $this->getBeforeOperatorRange($tokens, $tokens->getPrevMeaningfulToken($previousIndex))['start']; + } + + $range['start'] = $index; + + return $range; + } + + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range): void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + + private function isOperatorCommutative(Token $operatorToken): bool + { + if ($operatorToken->isGivenKind(\T_COALESCE)) { + return false; + } + + // check for commutative kinds + if ($operatorToken->equalsAny(['*', '|', '&', '^'])) { // note that for arrays in PHP `+` is not commutative + return true; + } + + // check for non-commutative kinds + if ($operatorToken->equalsAny(['-', '/', '.', '%', '+'])) { + return false; + } + + throw new \InvalidArgumentException(\sprintf('Not supported operator "%s".', $operatorToken->toJson())); + } + + private function belongsToSwitchOrAlternativeSyntax(AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer, Tokens $tokens, int $index): bool + { + $candidate = $index; + $index = $tokens->getPrevMeaningfulToken($candidate); + + if ($tokens[$index]->isGivenKind(\T_DEFAULT)) { + return true; + } + + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_CASE)) { + return true; + } + + return $alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $candidate); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php new file mode 100644 index 0000000..0f7adb7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php @@ -0,0 +1,202 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArrayPushFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts simple usages of `array_push($x, $y);` to `$x[] = $y;`.', + [new CodeSample("isTokenKindFound(\T_STRING) && $tokens->count() > 7; + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 7; $index > 0; --$index) { + if (!$tokens[$index]->equals([\T_STRING, 'array_push'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; // redeclare/override + } + + // meaningful before must be `getPrevMeaningfulToken($index); + $namespaceSeparatorIndex = null; + + if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) { + $namespaceSeparatorIndex = $index; + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->equalsAny([';', '{', '}', ')', [\T_OPEN_TAG]])) { + continue; + } + + // figure out where the arguments list opens + $openBraceIndex = $tokens->getNextMeaningfulToken($callIndex); + + // figure out where the arguments list closes + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openBraceIndex); + + // meaningful after `)` must be `;`, `? >` or nothing + $afterCloseBraceIndex = $tokens->getNextMeaningfulToken($closeBraceIndex); + + if (null !== $afterCloseBraceIndex && !$tokens[$afterCloseBraceIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + continue; + } + + // must have 2 arguments + + // first argument must be a variable (with possibly array indexing etc.), + // after that nothing meaningful should be there till the next `,` or `)` + // if `)` than we cannot fix it (it is a single argument call) + + $firstArgumentStop = $this->getFirstArgumentEnd($tokens, $openBraceIndex); + $firstArgumentStop = $tokens->getNextMeaningfulToken($firstArgumentStop); + + if (!$tokens[$firstArgumentStop]->equals(',')) { + continue; + } + + // second argument can be about anything but ellipsis, we must make sure there is not + // a third argument (or more) passed to `array_push` + + $secondArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStop); + $secondArgumentStop = $this->getSecondArgumentEnd($tokens, $secondArgumentStart, $closeBraceIndex); + + if (null === $secondArgumentStop) { + continue; + } + + // candidate is valid, replace tokens + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStop); + $tokens->insertAt( + $firstArgumentStop, + [ + new Token('['), + new Token(']'), + new Token([\T_WHITESPACE, ' ']), + new Token('='), + ], + ); + $tokens->clearTokenAndMergeSurroundingWhitespace($openBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); + + if (null !== $namespaceSeparatorIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex); + } + } + } + + private function getFirstArgumentEnd(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + while ($nextToken->equalsAny([ + '$', + '[', + '(', + [CT::T_ARRAY_INDEX_BRACE_OPEN], + [CT::T_DYNAMIC_PROP_BRACE_OPEN], + [CT::T_DYNAMIC_VAR_BRACE_OPEN], + [CT::T_NAMESPACE_OPERATOR], + [\T_NS_SEPARATOR], + [\T_STATIC], + [\T_STRING], + [\T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($nextToken); + + if (null !== $blockType) { + $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $index = $nextIndex; + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + if ($nextToken->isGivenKind(\T_OBJECT_OPERATOR)) { + return $this->getFirstArgumentEnd($tokens, $nextIndex); + } + + if ($nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + return $this->getFirstArgumentEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); + } + + return $index; + } + + /** + * @param int $endIndex boundary, i.e. tokens index of `)` + */ + private function getSecondArgumentEnd(Tokens $tokens, int $index, int $endIndex): ?int + { + if ($tokens[$index]->isGivenKind(\T_ELLIPSIS)) { + return null; + } + + for (; $index <= $endIndex; ++$index) { + $blockType = Tokens::detectBlockType($tokens[$index]); + + while (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + $index = $tokens->getNextMeaningfulToken($index); + $blockType = Tokens::detectBlockType($tokens[$index]); + } + + if ($tokens[$index]->equals(',') || $tokens[$index]->isGivenKind([\T_YIELD, \T_YIELD_FROM, \T_LOGICAL_AND, \T_LOGICAL_OR, \T_LOGICAL_XOR])) { + return null; + } + } + + return $endIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php new file mode 100644 index 0000000..87ad61f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BacktickToShellExecFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('`'); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts backtick operators to `shell_exec` calls.', + [ + new CodeSample( + <<<'EOT' + call()}`; + + EOT, + ), + ], + 'Conversion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before ExplicitStringVariableFixer, NativeFunctionInvocationFixer, SingleQuoteFixer. + */ + public function getPriority(): int + { + return 17; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $backtickStarted = false; + $backtickTokens = []; + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->equals('`')) { + if ($backtickStarted) { + $backtickTokens[$index] = $token; + } + + continue; + } + + $backtickTokens[$index] = $token; + + if ($backtickStarted) { + $this->fixBackticks($tokens, $backtickTokens); + $backtickTokens = []; + } + + $backtickStarted = !$backtickStarted; + } + } + + /** + * Override backtick code with corresponding double-quoted string. + * + * @param array $backtickTokens + */ + private function fixBackticks(Tokens $tokens, array $backtickTokens): void + { + // Track indices for final override + ksort($backtickTokens); + $openingBacktickIndex = array_key_first($backtickTokens); + $closingBacktickIndex = array_key_last($backtickTokens); + + // Strip enclosing backticks + array_shift($backtickTokens); + array_pop($backtickTokens); + + // Double-quoted strings are parsed differently if they contain + // variables or not, so we need to build the new token array accordingly + $count = \count($backtickTokens); + + $newTokens = [ + new Token([\T_STRING, 'shell_exec']), + new Token('('), + ]; + + if (1 !== $count) { + $newTokens[] = new Token('"'); + } + + foreach ($backtickTokens as $token) { + if (!$token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + $newTokens[] = $token; + + continue; + } + + $content = $token->getContent(); + // Escaping special chars depends on the context: too tricky + if (Preg::match('/[`"\']/u', $content)) { + return; + } + + $kind = \T_ENCAPSED_AND_WHITESPACE; + + if (1 === $count) { + $content = '"'.$content.'"'; + $kind = \T_CONSTANT_ENCAPSED_STRING; + } + + $newTokens[] = new Token([$kind, $content]); + } + + if (1 !== $count) { + $newTokens[] = new Token('"'); + } + + $newTokens[] = new Token(')'); + + $tokens->overrideRange($openingBacktickIndex, $closingBacktickIndex, $newTokens); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php new file mode 100644 index 0000000..6976546 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php @@ -0,0 +1,196 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\PregException; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Matteo Beccati + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EregToPregFixer extends AbstractFixer +{ + /** + * @var non-empty-list> the list of the ext/ereg function names, their preg equivalent and the preg modifier(s), if any + * all condensed in an array of arrays + */ + private const FUNCTIONS = [ + ['ereg', 'preg_match', ''], + ['eregi', 'preg_match', 'i'], + ['ereg_replace', 'preg_replace', ''], + ['eregi_replace', 'preg_replace', 'i'], + ['split', 'preg_split', ''], + ['spliti', 'preg_split', 'i'], + ]; + + /** + * @var non-empty-list the list of preg delimiters, in order of preference + */ + private const DELIMITERS = ['/', '#', '!']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace deprecated `ereg` regular expression functions with `preg`.', + [new CodeSample("isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $end = $tokens->count() - 1; + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (self::FUNCTIONS as $map) { + // the sequence is the function name, followed by "(" and a quoted string + $seq = [[\T_STRING, $map[0]], '(', [\T_CONSTANT_ENCAPSED_STRING]]; + $currIndex = 0; + + while (true) { + $match = $tokens->findSequence($seq, $currIndex, $end, false); + + // did we find a match? + if (null === $match) { + break; + } + + // findSequence also returns the tokens, but we're only interested in the indices, i.e.: + // 0 => function name, + // 1 => parenthesis "(" + // 2 => quoted string passed as 1st parameter + $match = array_keys($match); + \assert(isset($match[2])); + + // advance tokenizer cursor + $currIndex = $match[2]; + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $match[0])) { + continue; + } + + // ensure the first parameter is just a string (e.g. has nothing appended) + $next = $tokens->getNextMeaningfulToken($match[2]); + + if (null === $next || !$tokens[$next]->equalsAny([',', ')'])) { + continue; + } + + // convert to PCRE + $regexTokenContent = $tokens[$match[2]]->getContent(); + + if ('b' === $regexTokenContent[0] || 'B' === $regexTokenContent[0]) { + $quote = $regexTokenContent[1]; + $prefix = $regexTokenContent[0]; + $string = substr($regexTokenContent, 2, -1); + } else { + $quote = $regexTokenContent[0]; + $prefix = ''; + $string = substr($regexTokenContent, 1, -1); + } + + $delim = $this->getBestDelimiter($string); + $preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2]; + + // check if the preg is valid + if (!$this->checkPreg($preg)) { + continue; + } + + // modify function and argument + $tokens[$match[0]] = new Token([\T_STRING, $map[1]]); + $tokens[$match[2]] = new Token([\T_CONSTANT_ENCAPSED_STRING, $prefix.$quote.$preg.$quote]); + } + } + } + + /** + * Check the validity of a PCRE. + * + * @param string $pattern the regular expression + */ + private function checkPreg(string $pattern): bool + { + try { + Preg::match($pattern, ''); + + return true; + } catch (PregException $e) { + return false; + } + } + + /** + * Get the delimiter that would require the least escaping in a regular expression. + * + * @param string $pattern the regular expression + * + * @return string the preg delimiter + */ + private function getBestDelimiter(string $pattern): string + { + // try to find something that's not used + $delimiters = []; + + foreach (self::DELIMITERS as $k => $d) { + if (!str_contains($pattern, $d)) { + return $d; + } + + $delimiters[$d] = [substr_count($pattern, $d), $k]; + } + + // return the least used delimiter, using the position in the list as a tiebreaker + uasort($delimiters, static function (array $a, array $b): int { + if ($a[0] === $b[0]) { + return $a[1] <=> $b[1]; + } + + return $a[0] <=> $b[0]; + }); + + return array_key_first($delimiters); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php new file mode 100644 index 0000000..3546618 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php @@ -0,0 +1,180 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MbStrFunctionsFixer extends AbstractFixer +{ + /** + * list of the string-related function names and their mb_ equivalent. + * + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + private static array $functionsMap = [ + 'str_split' => ['alternativeName' => 'mb_str_split', 'argumentCount' => [1, 2, 3]], + 'stripos' => ['alternativeName' => 'mb_stripos', 'argumentCount' => [2, 3]], + 'stristr' => ['alternativeName' => 'mb_stristr', 'argumentCount' => [2, 3]], + 'strlen' => ['alternativeName' => 'mb_strlen', 'argumentCount' => [1]], + 'strpos' => ['alternativeName' => 'mb_strpos', 'argumentCount' => [2, 3]], + 'strrchr' => ['alternativeName' => 'mb_strrchr', 'argumentCount' => [2]], + 'strripos' => ['alternativeName' => 'mb_strripos', 'argumentCount' => [2, 3]], + 'strrpos' => ['alternativeName' => 'mb_strrpos', 'argumentCount' => [2, 3]], + 'strstr' => ['alternativeName' => 'mb_strstr', 'argumentCount' => [2, 3]], + 'strtolower' => ['alternativeName' => 'mb_strtolower', 'argumentCount' => [1]], + 'strtoupper' => ['alternativeName' => 'mb_strtoupper', 'argumentCount' => [1]], + 'substr' => ['alternativeName' => 'mb_substr', 'argumentCount' => [2, 3]], + 'substr_count' => ['alternativeName' => 'mb_substr_count', 'argumentCount' => [2, 3, 4]], + ]; + + /** + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + private array $functions; + + public function __construct() + { + parent::__construct(); + + if (\PHP_VERSION_ID >= 8_03_00) { + self::$functionsMap['str_pad'] = ['alternativeName' => 'mb_str_pad', 'argumentCount' => [1, 2, 3, 4]]; + } + + if (\PHP_VERSION_ID >= 8_04_00) { + self::$functionsMap['trim'] = ['alternativeName' => 'mb_trim', 'argumentCount' => [1, 2]]; + self::$functionsMap['ltrim'] = ['alternativeName' => 'mb_ltrim', 'argumentCount' => [1, 2]]; + self::$functionsMap['rtrim'] = ['alternativeName' => 'mb_rtrim', 'argumentCount' => [1, 2]]; + } + + $this->functions = array_filter( + self::$functionsMap, + static fn (array $mapping): bool => (new \ReflectionFunction($mapping['alternativeName']))->isInternal(), + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before NativeFunctionInvocationFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace non multibyte-safe functions with corresponding mb function.', + [ + new CodeSample( + <<<'PHP' + count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + + $lowercasedContent = strtolower($tokens[$index]->getContent()); + if (!isset($this->functions[$lowercasedContent])) { + continue; + } + + // is it a global function call? + if ($functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $openParenthesis = $tokens->getNextMeaningfulToken($index); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis); + $numberOfArguments = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + if (!\in_array($numberOfArguments, $this->functions[$lowercasedContent]['argumentCount'], true)) { + continue; + } + $tokens[$index] = new Token([\T_STRING, $this->functions[$lowercasedContent]['alternativeName']]); + + continue; + } + + // is it a global function import? + $functionIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$functionIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $functionIndex = $tokens->getPrevMeaningfulToken($functionIndex); + } + if (!$tokens[$functionIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + continue; + } + $tokens[$index] = new Token([\T_STRING, $this->functions[$lowercasedContent]['alternativeName']]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php new file mode 100644 index 0000000..b00691c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php @@ -0,0 +1,327 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * modernize_stripos?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * modernize_stripos: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Alexander M. Turek + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ModernizeStrposFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const REPLACEMENTS = [ + [ + 'operator' => [\T_IS_IDENTICAL, '==='], + 'operand' => [\T_LNUMBER, '0'], + 'replacement' => [\T_STRING, 'str_starts_with'], + 'negate' => false, + ], + [ + 'operator' => [\T_IS_NOT_IDENTICAL, '!=='], + 'operand' => [\T_LNUMBER, '0'], + 'replacement' => [\T_STRING, 'str_starts_with'], + 'negate' => true, + ], + [ + 'operator' => [\T_IS_NOT_IDENTICAL, '!=='], + 'operand' => [\T_STRING, 'false'], + 'replacement' => [\T_STRING, 'str_contains'], + 'negate' => false, + ], + [ + 'operator' => [\T_IS_IDENTICAL, '==='], + 'operand' => [\T_STRING, 'false'], + 'replacement' => [\T_STRING, 'str_contains'], + 'negate' => true, + ], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace `strpos()` and `stripos()` calls with `str_starts_with()` or `str_contains()` if possible.', + [ + new CodeSample( + <<<'PHP' + true], + ), + ], + null, + 'Risky if `strpos`, `stripos`, `str_starts_with`, `str_contains` or `strtolower` functions are overridden.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer, NoTrailingWhitespaceFixer, NotOperatorWithSpaceFixer, NotOperatorWithSuccessorSpaceFixer, PhpUnitDedicateAssertFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SpacesInsideParenthesesFixer. + * Must run after StrictComparisonFixer. + */ + public function getPriority(): int + { + return 37; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL]); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('modernize_stripos', 'Whether to modernize `stripos` calls as well.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $modernizeCandidates = [[\T_STRING, 'strpos']]; + if ($this->configuration['modernize_stripos']) { + $modernizeCandidates[] = [\T_STRING, 'stripos']; + } + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + // find candidate function call + if (!$tokens[$index]->equalsAny($modernizeCandidates, false) || !$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + // assert called with 2 arguments + $openIndex = $tokens->getNextMeaningfulToken($index); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + + if (2 !== \count($arguments)) { + continue; + } + + // check if part condition and fix if needed + $compareTokens = $this->getCompareTokens($tokens, $index, -1); // look behind + + if (null === $compareTokens) { + $compareTokens = $this->getCompareTokens($tokens, $closeIndex, 1); // look ahead + } + + if (null !== $compareTokens) { + $isCaseInsensitive = $tokens[$index]->equals([\T_STRING, 'stripos'], false); + $this->fixCall($tokens, $index, $compareTokens, $isCaseInsensitive); + } + } + } + + /** + * @param array{operator_index: int, operand_index: int} $operatorIndices + */ + private function fixCall(Tokens $tokens, int $functionIndex, array $operatorIndices, bool $isCaseInsensitive): void + { + foreach (self::REPLACEMENTS as $replacement) { + if (!$tokens[$operatorIndices['operator_index']]->equals($replacement['operator'])) { + continue; + } + + if (!$tokens[$operatorIndices['operand_index']]->equals($replacement['operand'], false)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operator_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operand_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionIndex); + + if ($replacement['negate']) { + $negateInsertIndex = $functionIndex; + + $prevFunctionIndex = $tokens->getPrevMeaningfulToken($functionIndex); + if ($tokens[$prevFunctionIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $negateInsertIndex = $prevFunctionIndex; + } + + $tokens->insertAt($negateInsertIndex, new Token('!')); + ++$functionIndex; + } + + $tokens->insertAt($functionIndex, new Token($replacement['replacement'])); + + if ($isCaseInsensitive) { + $this->wrapArgumentsWithStrToLower($tokens, $functionIndex); + } + + break; + } + } + + private function wrapArgumentsWithStrToLower(Tokens $tokens, int $functionIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $shouldAddNamespace = $tokens[$functionIndex - 1]->isGivenKind(\T_NS_SEPARATOR); + + $openIndex = $tokens->getNextMeaningfulToken($functionIndex); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + + $firstArgumentIndexStart = array_key_first($arguments); + \assert(isset($arguments[$firstArgumentIndexStart])); + + $firstArgumentIndexEnd = $arguments[$firstArgumentIndexStart] + 3 + ($shouldAddNamespace ? 1 : 0); + + $isSecondArgumentTokenWhiteSpace = $tokens[array_key_last($arguments)]->isGivenKind(\T_WHITESPACE); + + if ($isSecondArgumentTokenWhiteSpace) { + $secondArgumentIndexStart = $tokens->getNextMeaningfulToken(array_key_last($arguments)); + } else { + $secondArgumentIndexStart = array_key_last($arguments); + } + + $secondArgumentIndexStart += 3 + ($shouldAddNamespace ? 1 : 0); + $secondArgumentIndexEnd = $arguments[array_key_last($arguments)] + 6 + ($shouldAddNamespace ? 1 : 0) + ($isSecondArgumentTokenWhiteSpace ? 1 : 0); + + if ($shouldAddNamespace) { + $tokens->insertAt($firstArgumentIndexStart, new Token([\T_NS_SEPARATOR, '\\'])); + ++$firstArgumentIndexStart; + } + + $tokens->insertAt($firstArgumentIndexStart, [new Token([\T_STRING, 'strtolower']), new Token('(')]); + $tokens->insertAt($firstArgumentIndexEnd, new Token(')')); + + if ($shouldAddNamespace) { + $tokens->insertAt($secondArgumentIndexStart, new Token([\T_NS_SEPARATOR, '\\'])); + ++$secondArgumentIndexStart; + } + + $tokens->insertAt($secondArgumentIndexStart, [new Token([\T_STRING, 'strtolower']), new Token('(')]); + $tokens->insertAt($secondArgumentIndexEnd, new Token(')')); + } + + /** + * @param -1|1 $direction + * + * @return null|array{operator_index: int, operand_index: int} + */ + private function getCompareTokens(Tokens $tokens, int $offsetIndex, int $direction): ?array + { + $operatorIndex = $tokens->getMeaningfulTokenSibling($offsetIndex, $direction); + + if (null !== $operatorIndex && $tokens[$operatorIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $operatorIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + } + + if (null === $operatorIndex || !$tokens[$operatorIndex]->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL])) { + return null; + } + + $operandIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + \assert(\is_int($operandIndex)); + + $operand = $tokens[$operandIndex]; + + if (!$operand->equals([\T_LNUMBER, '0']) && !$operand->equals([\T_STRING, 'false'], false)) { + return null; + } + + $precedenceTokenIndex = $tokens->getMeaningfulTokenSibling($operandIndex, $direction); + + if (null !== $precedenceTokenIndex && $this->isOfHigherPrecedence($tokens[$precedenceTokenIndex])) { + return null; + } + + return ['operator_index' => $operatorIndex, 'operand_index' => $operandIndex]; + } + + private function isOfHigherPrecedence(Token $token): bool + { + return + $token->isGivenKind([ + \T_DEC, // -- + \T_INC, // ++ + \T_INSTANCEOF, // instanceof + \T_IS_GREATER_OR_EQUAL, // >= + \T_IS_SMALLER_OR_EQUAL, // <= + \T_POW, // ** + \T_SL, // << + \T_SR, // >> + ]) + || $token->equalsAny([ + '!', + '%', + '*', + '+', + '-', + '.', + '/', + '<', + '>', + '~', + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php new file mode 100644 index 0000000..154599e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php @@ -0,0 +1,350 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * sets?: list<'@all'|'@exif'|'@ftp'|'@IMAP'|'@internal'|'@ldap'|'@mbreg'|'@mysqli'|'@oci'|'@odbc'|'@openssl'|'@pcntl'|'@pg'|'@posix'|'@snmp'|'@sodium'|'@time'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * sets: list<'@all'|'@exif'|'@ftp'|'@IMAP'|'@internal'|'@ldap'|'@mbreg'|'@mysqli'|'@oci'|'@odbc'|'@openssl'|'@pcntl'|'@pg'|'@posix'|'@snmp'|'@sodium'|'@time'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Vladimir Reznichenko + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoAliasFunctionsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const SETS = [ + '@internal' => [ + 'diskfreespace' => 'disk_free_space', + + 'dns_check_record' => 'checkdnsrr', + 'dns_get_mx' => 'getmxrr', + + 'session_commit' => 'session_write_close', + + 'stream_register_wrapper' => 'stream_wrapper_register', + 'set_file_buffer' => 'stream_set_write_buffer', + 'socket_set_blocking' => 'stream_set_blocking', + 'socket_get_status' => 'stream_get_meta_data', + 'socket_set_timeout' => 'stream_set_timeout', + 'socket_getopt' => 'socket_get_option', + 'socket_setopt' => 'socket_set_option', + + 'chop' => 'rtrim', + 'close' => 'closedir', + 'doubleval' => 'floatval', + 'fputs' => 'fwrite', + 'get_required_files' => 'get_included_files', + 'ini_alter' => 'ini_set', + 'is_double' => 'is_float', + 'is_integer' => 'is_int', + 'is_long' => 'is_int', + 'is_real' => 'is_float', + 'is_writeable' => 'is_writable', + 'join' => 'implode', + 'key_exists' => 'array_key_exists', + 'magic_quotes_runtime' => 'set_magic_quotes_runtime', + 'pos' => 'current', + 'show_source' => 'highlight_file', + 'sizeof' => 'count', + 'strchr' => 'strstr', + 'user_error' => 'trigger_error', + ], + + '@IMAP' => [ + 'imap_create' => 'imap_createmailbox', + 'imap_fetchtext' => 'imap_body', + 'imap_header' => 'imap_headerinfo', + 'imap_listmailbox' => 'imap_list', + 'imap_listsubscribed' => 'imap_lsub', + 'imap_rename' => 'imap_renamemailbox', + 'imap_scan' => 'imap_listscan', + 'imap_scanmailbox' => 'imap_listscan', + ], + + '@ldap' => [ + 'ldap_close' => 'ldap_unbind', + 'ldap_modify' => 'ldap_mod_replace', + ], + + '@mysqli' => [ + 'mysqli_execute' => 'mysqli_stmt_execute', + 'mysqli_set_opt' => 'mysqli_options', + 'mysqli_escape_string' => 'mysqli_real_escape_string', + ], + + '@pg' => [ + 'pg_exec' => 'pg_query', + ], + + '@oci' => [ + 'oci_free_cursor' => 'oci_free_statement', + ], + + '@odbc' => [ + 'odbc_do' => 'odbc_exec', + 'odbc_field_precision' => 'odbc_field_len', + ], + + '@mbreg' => [ + 'mbereg' => 'mb_ereg', + 'mbereg_match' => 'mb_ereg_match', + 'mbereg_replace' => 'mb_ereg_replace', + 'mbereg_search' => 'mb_ereg_search', + 'mbereg_search_getpos' => 'mb_ereg_search_getpos', + 'mbereg_search_getregs' => 'mb_ereg_search_getregs', + 'mbereg_search_init' => 'mb_ereg_search_init', + 'mbereg_search_pos' => 'mb_ereg_search_pos', + 'mbereg_search_regs' => 'mb_ereg_search_regs', + 'mbereg_search_setpos' => 'mb_ereg_search_setpos', + 'mberegi' => 'mb_eregi', + 'mberegi_replace' => 'mb_eregi_replace', + 'mbregex_encoding' => 'mb_regex_encoding', + 'mbsplit' => 'mb_split', + ], + + '@openssl' => [ + 'openssl_get_publickey' => 'openssl_pkey_get_public', + 'openssl_get_privatekey' => 'openssl_pkey_get_private', + ], + + '@sodium' => [ + 'sodium_crypto_scalarmult_base' => 'sodium_crypto_box_publickey_from_secretkey', + ], + + '@exif' => [ + 'read_exif_data' => 'exif_read_data', + ], + + '@ftp' => [ + 'ftp_quit' => 'ftp_close', + ], + + '@posix' => [ + 'posix_errno' => 'posix_get_last_error', + ], + + '@pcntl' => [ + 'pcntl_errno' => 'pcntl_get_last_error', + ], + + '@time' => [ + 'mktime' => ['time', 0], + 'gmmktime' => ['time', 0], + ], + ]; + + /** + * @var array stores alias (key) - master (value) functions mapping + */ + private array $aliases = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Master functions shall be used instead of aliases.', + [ + new CodeSample( + <<<'PHP' + ['@mbreg']], + ), + ], + null, + 'Risky when any of the alias functions are overridden.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before ImplodeCallFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return 40; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->aliases = []; + + foreach ($this->configuration['sets'] as $set) { + if ('@all' === $set) { + $this->aliases = self::mergeSets(self::SETS); + + break; + } + + \assert(isset(self::SETS[$set])); + + $this->aliases = array_merge($this->aliases, self::SETS[$set]); + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($tokens->findGivenKind(\T_STRING) as $index => $token) { + // check mapping hit + $tokenContent = strtolower($token->getContent()); + + if (!isset($this->aliases[$tokenContent])) { + continue; + } + + // skip expressions without parameters list + $openParenthesis = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$openParenthesis]->equals('(')) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + if (\is_array($this->aliases[$tokenContent])) { + [$alias, $numberOfArguments] = $this->aliases[$tokenContent]; + + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis)); + + if ($numberOfArguments !== $count) { + continue; + } + } else { + $alias = $this->aliases[$tokenContent]; + } + + $tokens[$index] = new Token([\T_STRING, $alias]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $sets = [ + '@all' => 'all listed sets', + '@internal' => 'native functions', + '@exif' => 'EXIF functions', + '@ftp' => 'FTP functions', + '@IMAP' => 'IMAP functions', + '@ldap' => 'LDAP functions', + '@mbreg' => 'from `ext-mbstring`', + '@mysqli' => 'mysqli functions', + '@oci' => 'oci functions', + '@odbc' => 'odbc functions', + '@openssl' => 'openssl functions', + '@pcntl' => 'PCNTL functions', + '@pg' => 'pg functions', + '@posix' => 'POSIX functions', + '@snmp' => 'SNMP functions', // @TODO Remove on next major 4.0 as this set is now empty + '@sodium' => 'libsodium functions', + '@time' => 'time functions', + ]; + + $list = "List of sets to fix. Defined sets are:\n\n"; + + foreach ($sets as $set => $description) { + $list .= \sprintf("* `%s` (%s);\n", $set, $description); + } + + $list = rtrim($list, ";\n").'.'; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sets', $list)) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(array_keys($sets))]) + ->setDefault(['@internal', '@IMAP', '@pg']) + ->getOption(), + ]); + } + + /** + * @param array> $sets + * + * @return array + */ + private static function mergeSets(array $sets): array + { + return array_merge(...array_values($sets)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php new file mode 100644 index 0000000..a668d88 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoAliasLanguageConstructCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Master language constructs shall be used instead of aliases.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_EXIT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_EXIT)) { + continue; + } + + if ('exit' === strtolower($token->getContent())) { + continue; + } + + $tokens[$index] = new Token([\T_EXIT, 'exit']); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php new file mode 100644 index 0000000..74af0d3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php @@ -0,0 +1,144 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * use?: 'echo'|'print', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * use: 'echo'|'print', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Sullivan Senechal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoMixedEchoPrintFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var T_ECHO|T_PRINT + */ + private int $candidateTokenType; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Either language construct `print` or `echo` should be used.', + [ + new CodeSample(" 'print']), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after EchoTagSyntaxFixer, NoUselessPrintfFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenType); + } + + protected function configurePostNormalisation(): void + { + $this->candidateTokenType = 'echo' === $this->configuration['use'] ? \T_PRINT : \T_ECHO; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($this->candidateTokenType)) { + if (\T_PRINT === $this->candidateTokenType) { + $this->fixPrintToEcho($tokens, $index); + } else { + $this->fixEchoToPrint($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use', 'The desired language construct.')) + ->setAllowedValues(['print', 'echo']) + ->setDefault('echo') + ->getOption(), + ]); + } + + private function fixEchoToPrint(Tokens $tokens, int $index): void + { + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + $endTokenIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + $canBeConverted = true; + + for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) { + if ($tokens[$i]->equalsAny(['(', [CT::T_ARRAY_BRACKET_OPEN]])) { + $blockType = Tokens::detectBlockType($tokens[$i]); + $i = $tokens->findBlockEnd($blockType['type'], $i); + } + + if ($tokens[$i]->equals(',')) { + $canBeConverted = false; + + break; + } + } + + if (false === $canBeConverted) { + return; + } + + $tokens[$index] = new Token([\T_PRINT, 'print']); + } + + private function fixPrintToEcho(Tokens $tokens, int $index): void + { + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny([';', '{', '}', ')', [\T_OPEN_TAG], [\T_ELSE]])) { + return; + } + + $tokens[$index] = new Token([\T_ECHO, 'echo']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php new file mode 100644 index 0000000..f7c3da8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php @@ -0,0 +1,223 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PowToExponentiationFixer extends AbstractFunctionReferenceFixer +{ + public function isCandidate(Tokens $tokens): bool + { + // minimal candidate to fix is seven tokens: pow(x,y); + return $tokens->count() > 7 && $tokens->isTokenKindFound(\T_STRING); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `pow` to the `**` operator.', + [ + new CodeSample( + "findPowCalls($tokens); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $numberOfTokensAdded = 0; + $previousCloseParenthesisIndex = \count($tokens); + + foreach (array_reverse($candidates) as $candidate) { + // if in the previous iteration(s) tokens were added to the collection and this is done within the tokens + // indices of the current candidate than the index of the close ')' of the candidate has moved and so + // the index needs to be updated + if ($previousCloseParenthesisIndex < $candidate[2]) { + $previousCloseParenthesisIndex = $candidate[2]; + $candidate[2] += $numberOfTokensAdded; + } else { + $previousCloseParenthesisIndex = $candidate[2]; + $numberOfTokensAdded = 0; + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); + + if (2 !== \count($arguments)) { + continue; + } + + for ($i = $candidate[1]; $i < $candidate[2]; ++$i) { + if ($tokens[$i]->isGivenKind(\T_ELLIPSIS)) { + continue 2; + } + } + + $numberOfTokensAdded += $this->fixPowToExponentiation( + $tokens, + $candidate[0], // functionNameIndex, + $candidate[1], // openParenthesisIndex, + $candidate[2], // closeParenthesisIndex, + $arguments, + ); + } + } + + /** + * @return list + */ + private function findPowCalls(Tokens $tokens): array + { + $candidates = []; + + // Minimal candidate to fix is seven tokens: pow(x,y); + $end = \count($tokens) - 6; + + // First possible location is after the open token: 1 + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('pow', $tokens, $i, $end); + + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + return $candidates; + } + + /** + * @param array $arguments + * + * @return int number of tokens added to the collection + */ + private function fixPowToExponentiation(Tokens $tokens, int $functionNameIndex, int $openParenthesisIndex, int $closeParenthesisIndex, array $arguments): int + { + // find the argument separator ',' directly after the last token of the first argument; + // replace it with T_POW '**' + \assert(false !== reset($arguments)); + $tokens[$tokens->getNextTokenOfKind(reset($arguments), [','])] = new Token([\T_POW, '**']); + + // clean up the function call tokens prt. I + $tokens->clearAt($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearAt($previousIndex); // trailing ',' in function call (PHP 7.3) + } + + $added = 0; + + // check if the arguments need to be wrapped in parentheses + foreach (array_reverse($arguments, true) as $argumentStartIndex => $argumentEndIndex) { + if ($this->isParenthesisNeeded($tokens, $argumentStartIndex, $argumentEndIndex)) { + $tokens->insertAt($argumentEndIndex + 1, new Token(')')); + $tokens->insertAt($argumentStartIndex, new Token('(')); + $added += 2; + } + } + + // clean up the function call tokens prt. II + $tokens->clearAt($openParenthesisIndex); + $tokens->clearAt($functionNameIndex); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearAt($prevMeaningfulTokenIndex); + } + + return $added; + } + + private function isParenthesisNeeded(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): bool + { + static $allowedKinds = null; + + if (null === $allowedKinds) { + $allowedKinds = $this->getAllowedKinds(); + } + + for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind($allowedKinds) || $tokens->isEmptyAt($i)) { + continue; + } + + $blockType = Tokens::detectBlockType($tokens[$i]); + + if (null !== $blockType) { + $i = $tokens->findBlockEnd($blockType['type'], $i); + + continue; + } + + if ($tokens[$i]->equals('$')) { + $i = $tokens->getNextMeaningfulToken($i); + if ($tokens[$i]->isGivenKind(CT::T_DYNAMIC_VAR_BRACE_OPEN)) { + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, $i); + + continue; + } + } + + if ($tokens[$i]->equals('+') && $tokens->getPrevMeaningfulToken($i) < $argumentStartIndex) { + continue; + } + + return true; + } + + return false; + } + + /** + * @return non-empty-list + */ + private function getAllowedKinds(): array + { + return [ + \T_DNUMBER, \T_LNUMBER, \T_VARIABLE, \T_STRING, \T_CONSTANT_ENCAPSED_STRING, \T_DOUBLE_CAST, + \T_INT_CAST, \T_INC, \T_DEC, \T_NS_SEPARATOR, \T_WHITESPACE, \T_DOUBLE_COLON, \T_LINE, \T_COMMENT, \T_DOC_COMMENT, + CT::T_NAMESPACE_OPERATOR, + ...Token::getObjectOperatorKinds(), + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php new file mode 100644 index 0000000..06a4e37 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php @@ -0,0 +1,166 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * replacements?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * replacements: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Vladimir Reznichenko + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array> + */ + private const ARGUMENT_COUNTS = [ + 'mt_getrandmax' => [0], + 'getrandmax' => [0], + 'mt_rand' => [1, 2], + 'rand' => [0, 2], + 'srand' => [0, 1], + 'mt_srand' => [0, 1], + 'random_int' => [0, 2], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.', + [ + new CodeSample(" ['getrandmax' => 'mt_getrandmax']], + ), + new CodeSample( + " ['rand' => 'random_int']], + ), + ], + null, + 'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.', + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) { + if ($functionIdentity === $functionReplacement) { + continue; + } + + $currIndex = 0; + + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + + \assert(isset(self::ARGUMENT_COUNTS[$functionIdentity])); // for PHPStan + + if (!\in_array($count, self::ARGUMENT_COUNTS[$functionIdentity], true)) { + continue 2; + } + + // analysing cursor shift, so nested calls could be processed + $currIndex = $openParenthesis; + $tokens[$functionName] = new Token([\T_STRING, $functionReplacement]); + + if (0 === $count && 'random_int' === $functionReplacement) { + $tokens->insertAt($currIndex + 1, [ + new Token([\T_LNUMBER, '0']), + new Token(','), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_STRING, 'getrandmax']), + new Token('('), + new Token(')'), + ]); + + $currIndex += 6; + } + } while (null !== $currIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName => $replacement) { + if (!\array_key_exists($functionName, self::ARGUMENT_COUNTS)) { + throw new InvalidOptionsException(\sprintf( + 'Function "%s" is not handled by the fixer.', + $functionName, + )); + } + } + + return true; + }]) + ->setDefault(Future::getV4OrV3( + [ + 'mt_getrandmax' => 'getrandmax', + 'mt_rand' => 'random_int', + 'mt_srand' => 'srand', + 'rand' => 'random_int', + ], + [ + 'getrandmax' => 'mt_getrandmax', + 'rand' => 'mt_rand', + 'srand' => 'mt_srand', + ], + )) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php new file mode 100644 index 0000000..b874e9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php @@ -0,0 +1,245 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SetTypeToCastFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast shall be used, not `settype`.', + [ + new CodeSample( + <<<'PHP' + isAllTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_STRING, \T_VARIABLE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $map = [ + 'array' => [\T_ARRAY_CAST, '(array)'], + 'bool' => [\T_BOOL_CAST, '(bool)'], + 'boolean' => [\T_BOOL_CAST, '(bool)'], + 'double' => [\T_DOUBLE_CAST, '(float)'], + 'float' => [\T_DOUBLE_CAST, '(float)'], + 'int' => [\T_INT_CAST, '(int)'], + 'integer' => [\T_INT_CAST, '(int)'], + 'object' => [\T_OBJECT_CAST, '(object)'], + 'string' => [\T_STRING_CAST, '(string)'], + // note: `'null' is dealt with later on + ]; + + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach (array_reverse($this->findSettypeCalls($tokens)) as $candidate) { + $functionNameIndex = $candidate[0]; + + $arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]); + if (2 !== \count($arguments)) { + continue; // function must be overridden or used incorrectly + } + + $prev = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if (!$tokens[$prev]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) { + continue; // return value of the function is used + } + + reset($arguments); + + // --- Test first argument -------------------- + + $firstArgumentStart = key($arguments); + if ($tokens[$firstArgumentStart]->isComment() || $tokens[$firstArgumentStart]->isWhitespace()) { + $firstArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStart); + } + + if (!$tokens[$firstArgumentStart]->isGivenKind(\T_VARIABLE)) { + continue; // settype only works with variables pass by reference, function must be overridden + } + + $commaIndex = $tokens->getNextMeaningfulToken($firstArgumentStart); + + if (null === $commaIndex || !$tokens[$commaIndex]->equals(',')) { + continue; // first argument is complex statement; function must be overridden + } + + // --- Test second argument ------------------- + + next($arguments); + $secondArgumentStart = key($arguments); + $secondArgumentEnd = $arguments[$secondArgumentStart]; + + if ($tokens[$secondArgumentStart]->isComment() || $tokens[$secondArgumentStart]->isWhitespace()) { + $secondArgumentStart = $tokens->getNextMeaningfulToken($secondArgumentStart); + } + + if ( + !$tokens[$secondArgumentStart]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) + || $tokens->getNextMeaningfulToken($secondArgumentStart) < $secondArgumentEnd + ) { + continue; // second argument is of the wrong type or is a (complex) statement of some sort (function is overridden) + } + + // --- Test type ------------------------------ + + $type = strtolower(trim($tokens[$secondArgumentStart]->getContent(), '"\'')); + + if ('null' !== $type && !isset($map[$type])) { + continue; // we don't know how to map + } + + // --- Fixing --------------------------------- + + $argumentToken = $tokens[$firstArgumentStart]; + + $this->removeSettypeCall( + $tokens, + $functionNameIndex, + $candidate[1], + $firstArgumentStart, + $commaIndex, + $secondArgumentStart, + $candidate[2], + ); + + if ('null' === $type) { + $this->fixSettypeNullCall($tokens, $functionNameIndex, $argumentToken); + } else { + $this->fixSettypeCall($tokens, $functionNameIndex, $argumentToken, new Token($map[$type])); + } + } + } + + /** + * @return list + */ + private function findSettypeCalls(Tokens $tokens): array + { + $candidates = []; + + $end = \count($tokens); + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('settype', $tokens, $i, $end); + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + return $candidates; + } + + private function removeSettypeCall( + Tokens $tokens, + int $functionNameIndex, + int $openParenthesisIndex, + int $firstArgumentStart, + int $commaIndex, + int $secondArgumentStart, + int $closeParenthesisIndex + ): void { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + $prevIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + if ($tokens[$prevIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($secondArgumentStart); + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStart); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + $tokens->clearAt($functionNameIndex); // we'll be inserting here so no need to merge the space tokens + $tokens->clearEmptyTokens(); + } + + private function fixSettypeCall( + Tokens $tokens, + int $functionNameIndex, + Token $argumentToken, + Token $castToken + ): void { + $tokens->insertAt( + $functionNameIndex, + [ + clone $argumentToken, + new Token([\T_WHITESPACE, ' ']), + new Token('='), + new Token([\T_WHITESPACE, ' ']), + $castToken, + new Token([\T_WHITESPACE, ' ']), + clone $argumentToken, + ], + ); + + $tokens->removeTrailingWhitespace($functionNameIndex + 6); // 6 = number of inserted tokens -1 for offset correction + } + + private function fixSettypeNullCall( + Tokens $tokens, + int $functionNameIndex, + Token $argumentToken + ): void { + $tokens->insertAt( + $functionNameIndex, + [ + clone $argumentToken, + new Token([\T_WHITESPACE, ' ']), + new Token('='), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_STRING, 'null']), + ], + ); + + $tokens->removeTrailingWhitespace($functionNameIndex + 4); // 4 = number of inserted tokens -1 for offset correction + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php new file mode 100644 index 0000000..b8cf7bf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * syntax?: 'long'|'short', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * syntax: 'long'|'short', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var CT::T_ARRAY_BRACKET_OPEN|T_ARRAY + */ + private $candidateTokenKind; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP arrays should be declared using the configured syntax.', + [ + new CodeSample( + " 'long'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, NoWhitespaceInEmptyArrayFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 37; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + + protected function configurePostNormalisation(): void + { + $this->resolveCandidateTokenKind(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { + if ('short' === $this->configuration['syntax']) { + $this->fixToShortArraySyntax($tokens, $index); + } else { + $this->fixToLongArraySyntax($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` array syntax.')) + ->setAllowedValues(['long', 'short']) + ->setDefault('short') + ->getOption(), + ]); + } + + private function fixToLongArraySyntax(Tokens $tokens, int $index): void + { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + $tokens[$index] = new Token('('); + $tokens[$closeIndex] = new Token(')'); + + $tokens->insertAt($index, new Token([\T_ARRAY, 'array'])); + } + + private function fixToShortArraySyntax(Tokens $tokens, int $index): void + { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_ARRAY_BRACKET_OPEN, '[']); + $tokens[$closeIndex] = new Token([CT::T_ARRAY_BRACKET_CLOSE, ']']); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + private function resolveCandidateTokenKind(): void + { + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_ARRAY_BRACKET_OPEN : \T_ARRAY; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php new file mode 100644 index 0000000..98c98d4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Carlos Cirello + * @author Dariusz Rumiński + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Operator `=>` should not be surrounded by multi-line whitespaces.', + [new CodeSample(" 2);\n")], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, MethodArgumentSpaceFixer. + */ + public function getPriority(): int + { + return 31; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOUBLE_ARROW); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOUBLE_ARROW)) { + continue; + } + + if (!$tokens[$index - 2]->isComment() || str_starts_with($tokens[$index - 2]->getContent(), '/*')) { + $this->fixWhitespace($tokens, $index - 1); + } + + // do not move anything about if there is a comment following the whitespace + if (!$tokens[$index + 2]->isComment()) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + + private function fixWhitespace(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if ($token->isWhitespace() && !$token->isWhitespace(" \t")) { + $tokens[$index] = new Token([\T_WHITESPACE, rtrim($token->getContent()).' ']); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php new file mode 100644 index 0000000..1e666b6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @author Dariusz Rumiński + * @author Sebastiaan Stok + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingCommaInSinglelineArrayFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP single-line arrays should not have trailing comma.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array']]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php new file mode 100644 index 0000000..6523dc3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php @@ -0,0 +1,156 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * after_heredoc?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * after_heredoc: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Adam Marczuk + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoWhitespaceBeforeCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In array declaration, there MUST NOT be a whitespace before each comma.', + [ + new CodeSample(" true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + $this->fixSpacing($index, $tokens); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + ]); + } + + /** + * Method to fix spacing in array declaration. + */ + private function fixSpacing(int $index, Tokens $tokens): void + { + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $startIndex = $index; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $startIndex); + } else { + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startIndex); + } + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $i = $this->skipNonArrayElements($i, $tokens); + $currentToken = $tokens[$i]; + $prevIndex = $tokens->getPrevNonWhitespace($i - 1); + + if ( + $currentToken->equals(',') && !$tokens[$prevIndex]->isComment() + && (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC)) + ) { + $tokens->removeLeadingWhitespace($i); + } + } + } + + /** + * Method to move index over the non-array elements like function calls or function declarations. + */ + private function skipNonArrayElements(int $index, Tokens $tokens): int + { + if ($tokens[$index]->equals('}')) { + return $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + } + + if ($tokens[$index]->equals(')')) { + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $startIndex = $tokens->getPrevMeaningfulToken($startIndex); + if (!$tokens[$startIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + return $startIndex; + } + } + + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + + return $index; + } + + private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + + $current = $tokens[$index]; + } while ($current->isGivenKind(\T_STRING) || $current->equals(',')); + + return $current->isGivenKind(\T_IMPLEMENTS); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceInEmptyArrayFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceInEmptyArrayFixer.php new file mode 100644 index 0000000..d80e009 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceInEmptyArrayFixer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jeremiasz Major + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoWhitespaceInEmptyArrayFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty arrays should not contain only whitespace.', + [new CodeSample("isTokenKindFound(CT::T_ARRAY_BRACKET_OPEN); + } + + /** + * {@inheritdoc} + * + * Must run after ArraySyntaxFixer, NoEmptyCommentFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_CLOSE)) { + continue; + } + + if ($tokens->getPrevNonWhitespace($index) !== $index - 2) { + continue; + } + + if (!$tokens[$index - 2]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + continue; + } + + $tokens->clearAt($index - 1); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php new file mode 100644 index 0000000..90055e5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NormalizeIndexBraceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Array index should always be written by using square braces.', + [new VersionSpecificCodeSample( + "isTokenKindFound(CT::T_ARRAY_INDEX_BRACE_OPEN); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(CT::T_ARRAY_INDEX_BRACE_OPEN)) { + $tokens[$index] = new Token('['); + } elseif ($token->isGivenKind(CT::T_ARRAY_INDEX_BRACE_CLOSE)) { + $tokens[$index] = new Token(']'); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php new file mode 100644 index 0000000..5e9526a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ReturnToYieldFromFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReturnToYieldFromFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'If the function explicitly returns an array, and has the return type `iterable`, then `yield from` must be used instead of `return`.', + [ + new CodeSample( + <<<'PHP' + isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]) && $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN]); + } + + /** + * {@inheritdoc} + * + * Must run before YieldFromArrayToYieldsFixer. + * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens->findGivenKind(\T_RETURN) as $index => $token) { + if (!$this->shouldBeFixed($tokens, $index)) { + continue; + } + + $tokens[$index] = new Token([\T_YIELD_FROM, 'yield from']); + } + } + + private function shouldBeFixed(Tokens $tokens, int $returnIndex): bool + { + $arrayStartIndex = $tokens->getNextMeaningfulToken($returnIndex); + if (!$tokens[$arrayStartIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + return false; + } + + if ($tokens[$arrayStartIndex]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $arrayStartIndex); + } else { + $arrayOpenParenthesisIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']); + $arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $arrayOpenParenthesisIndex); + } + + $functionEndIndex = $arrayEndIndex; + do { + $functionEndIndex = $tokens->getNextMeaningfulToken($functionEndIndex); + } while (null !== $functionEndIndex && $tokens[$functionEndIndex]->equals(';')); + if (null === $functionEndIndex || !$tokens[$functionEndIndex]->equals('}')) { + return false; + } + + $functionStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $functionEndIndex); + + $returnTypeIndex = $tokens->getPrevMeaningfulToken($functionStartIndex); + if (!$tokens[$returnTypeIndex]->isGivenKind(\T_STRING)) { + return false; + } + + if ('iterable' !== strtolower($tokens[$returnTypeIndex]->getContent())) { + return false; + } + + $beforeReturnTypeIndex = $tokens->getPrevMeaningfulToken($returnTypeIndex); + + return $tokens[$beforeReturnTypeIndex]->isGivenKind(CT::T_TYPE_COLON); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php new file mode 100644 index 0000000..7f79810 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jared Henderson + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TrimArraySpacesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Arrays should be formatted like function/method arguments, without leading or trailing single line space.', + [new CodeSample("isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) { + if ($tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN])) { + self::fixArray($tokens, $index); + } + } + } + + /** + * Method to trim leading/trailing whitespace within single line arrays. + */ + private static function fixArray(Tokens $tokens, int $index): void + { + $startIndex = $index; + + if ($tokens[$startIndex]->isGivenKind(\T_ARRAY)) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startIndex); + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_DESTRUCTURING_BRACKET_OPEN)) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DESTRUCTURING_BRACKET, $startIndex); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $startIndex); + } + + $nextIndex = $startIndex + 1; + $nextToken = $tokens[$nextIndex]; + $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex); + $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex]; + $tokenAfterNextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex + 1]; + + $prevIndex = $endIndex - 1; + $prevToken = $tokens[$prevIndex]; + $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex); + $prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex]; + + if ( + $nextToken->isWhitespace(" \t") + && ( + !$nextNonWhitespaceToken->isComment() + || $nextNonWhitespaceIndex === $prevNonWhitespaceIndex + || $tokenAfterNextNonWhitespaceToken->isWhitespace(" \t") + || str_starts_with($nextNonWhitespaceToken->getContent(), '/*') + ) + ) { + $tokens->clearAt($nextIndex); + } + + if ( + $prevToken->isWhitespace(" \t") + && !$prevNonWhitespaceToken->equals(',') + ) { + $tokens->clearAt($prevIndex); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php new file mode 100644 index 0000000..9ea9def --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php @@ -0,0 +1,152 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ensure_single_space?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ensure_single_space: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Adam Marczuk + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In array declaration, there MUST be a whitespace after each comma.', + [ + new CodeSample(" true]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ensure_single_space', 'If there are only horizontal whitespaces after the comma then ensure it is a single space.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensToInsert = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $startIndex = $index; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $startIndex); + } else { + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startIndex); + } + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $i = $this->skipNonArrayElements($i, $tokens); + if (!$tokens[$i]->equals(',')) { + continue; + } + if (!$tokens[$i + 1]->isWhitespace()) { + $tokensToInsert[$i + 1] = new Token([\T_WHITESPACE, ' ']); + } elseif ( + true === $this->configuration['ensure_single_space'] + && ' ' !== $tokens[$i + 1]->getContent() + && Preg::match('/^\h+$/', $tokens[$i + 1]->getContent()) + && (!$tokens[$i + 2]->isComment() || Preg::match('/^\h+$/', $tokens[$i + 3]->getContent())) + ) { + $tokens[$i + 1] = new Token([\T_WHITESPACE, ' ']); + } + } + } + + if ([] !== $tokensToInsert) { + $tokens->insertSlices($tokensToInsert); + } + } + + /** + * Method to move index over the non-array elements like function calls or function declarations. + * + * @return int New index + */ + private function skipNonArrayElements(int $index, Tokens $tokens): int + { + if ($tokens[$index]->equals('}')) { + return $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + } + + if ($tokens[$index]->equals(')')) { + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $startIndex = $tokens->getPrevMeaningfulToken($startIndex); + if (!$tokens[$startIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + return $startIndex; + } + } + + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + + return $index; + } + + private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + + $current = $tokens[$index]; + } while ($current->isGivenKind(\T_STRING) || $current->equals(',')); + + return $current->isGivenKind(\T_IMPLEMENTS); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php new file mode 100644 index 0000000..52ae1a5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php @@ -0,0 +1,195 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class YieldFromArrayToYieldsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Yield from array must be unpacked to series of yields.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_YIELD_FROM); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoMultipleStatementsPerLineFixer, NoWhitespaceInBlankLineFixer, StatementIndentationFixer. + * Must run after ReturnToYieldFromFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** + * @var array $inserts + */ + $inserts = []; + + foreach ($this->getYieldsFromToUnpack($tokens) as $index => [$startIndex, $endIndex]) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + if ($tokens[$startIndex]->equals('(')) { + $prevStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($prevStartIndex); // clear `array` from `array(` + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($endIndex); + + $arrayHasTrailingComma = false; + + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + + $inserts[$startIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])]; + + foreach ($this->findArrayItemCommaIndex( + $tokens, + $startIndex, + $tokens->getPrevMeaningfulToken($endIndex), + ) as $commaIndex) { + $nextItemIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($nextItemIndex < $endIndex) { + $inserts[$nextItemIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])]; + $tokens[$commaIndex] = new Token(';'); + } else { + $arrayHasTrailingComma = true; + // array has trailing comma - we replace it with `;` (as it's best fit to put it) + $tokens[$commaIndex] = new Token(';'); + } + } + + // there was a trailing comma, so we do not need original `;` after initial array structure + if (true === $arrayHasTrailingComma) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($endIndex)); + } + } + + $tokens->insertSlices($inserts); + } + + /** + * @return iterable + */ + private function getYieldsFromToUnpack(Tokens $tokens): iterable + { + $tokensCount = $tokens->count(); + $index = 0; + while (++$index < $tokensCount) { + if (!$tokens[$index]->isGivenKind(\T_YIELD_FROM)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) { + continue; + } + + $arrayStartIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$arrayStartIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + continue; + } + + if ($tokens[$arrayStartIndex]->isGivenKind(\T_ARRAY)) { + $startIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startIndex); + } else { + $startIndex = $arrayStartIndex; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $startIndex); + } + + // is there empty "yield from []" ? + if ($endIndex === $tokens->getNextMeaningfulToken($startIndex)) { + continue; + } + + // is there any nested "yield from"? + if ([] !== $tokens->findGivenKind(\T_YIELD_FROM, $startIndex, $endIndex)) { + continue; + } + + yield $index => [$startIndex, $endIndex]; + } + } + + /** + * @return iterable + */ + private function findArrayItemCommaIndex(Tokens $tokens, int $startIndex, int $endIndex): iterable + { + for ($index = $startIndex; $index <= $endIndex; ++$index) { + $token = $tokens[$index]; + + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + + if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) { + $index = $tokens->findBlockEnd($blockDefinitionProbe['type'], $index); + + continue; + } + + if (!$tokens[$index]->equals(',')) { + continue; + } + + yield $index; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeBlockNoSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeBlockNoSpacesFixer.php new file mode 100644 index 0000000..8c62b84 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeBlockNoSpacesFixer.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\AttributeNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Albin Kester + * + * @see https://www.php-fig.org/per/coding-style/#121-basics + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AttributeBlockNoSpacesFixer extends AbstractFixer +{ + use IndentationTrait; + + public function getDefinition(): FixerDefinition + { + return new FixerDefinition( + 'Remove spaces before and after the attributes block.', + [ + new CodeSample( + 'isTokenKindFound(FCT::T_ATTRIBUTE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $index = 0; + + while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) { + $toDelete = []; + + $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index); + + $index = $attributeAnalysis->getOpeningBracketIndex(); + $token = $tokens[$index]; + \assert($token->isGivenKind([\T_ATTRIBUTE])); + + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + for ($i = $index + 1; $i < $nextTokenIndex; ++$i) { + if (!$tokens[$i]->isWhitespace()) { + $toDelete = []; + + break; + } + $toDelete[] = $i; + } + unset($i); + + $index = $attributeAnalysis->getClosingBracketIndex(); + $token = $tokens[$index]; + \assert($token->isGivenKind([CT::T_ATTRIBUTE_CLOSE])); + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($index); + for ($i = $prevTokenIndex + 1; $i < $index; ++$i) { + if (!$tokens[$i]->isWhitespace()) { + $toDelete = []; + + break; + } + $toDelete[] = $i; + } + unset($i); + + foreach ($toDelete as $i) { + $tokens->clearAt($i); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php new file mode 100644 index 0000000..880272c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php @@ -0,0 +1,139 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\AttributeNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * use_parentheses?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * use_parentheses: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author HypeMC + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AttributeEmptyParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP attributes declared without arguments must (not) be followed by empty parentheses.', + [ + new CodeSample(" true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_parentheses', 'Whether attributes should be followed by parentheses or not.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $index = 0; + + while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) { + $nextIndex = $index; + + do { + $parenthesesIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + + if (true === $this->configuration['use_parentheses']) { + $this->ensureParenthesesAt($tokens, $parenthesesIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $parenthesesIndex); + } + + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + + // Find closing parentheses, we need to do this in case there's a comma inside the parentheses + if ($tokens[$nextIndex]->equals('(')) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, [',', [CT::T_ATTRIBUTE_CLOSE]]); + } + + // In case there's a comma right before T_ATTRIBUTE_CLOSE + if (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + } while (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)); + } + } + + private function ensureParenthesesAt(Tokens $tokens, int $index): void + { + if ($tokens[$index]->equals('(')) { + return; + } + + $tokens->insertAt( + $tokens->getPrevMeaningfulToken($index) + 1, + [new Token('('), new Token(')')], + ); + } + + private function ensureNoParenthesesAt(Tokens $tokens, int $index): void + { + if (!$tokens[$index]->equals('(')) { + return; + } + + $closingIndex = $tokens->getNextMeaningfulToken($index); + + // attribute has arguments - parentheses can not be removed + if (!$tokens[$closingIndex]->equals(')')) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/GeneralAttributeRemoveFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/GeneralAttributeRemoveFixer.php new file mode 100644 index 0000000..6a7d8e8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/GeneralAttributeRemoveFixer.php @@ -0,0 +1,145 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\AttributeNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-import-type _AttributeItems from AttributeAnalysis + * @phpstan-import-type _AttributeItem from AttributeAnalysis + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * attributes?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * attributes: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Raffaele Carelle + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GeneralAttributeRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes configured attributes by their respective FQN.', + [ + new CodeSample( + <<<'PHP' + ['\A\B\Foo']], + ), + new CodeSample( + <<<'PHP' + ['\A\B\Foo', 'A\B\Bar']], + ), + ], + ); + } + + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $index = 0; + + while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) { + $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index); + + $endIndex = $attributeAnalysis->getEndIndex(); + + $removedCount = 0; + foreach ($attributeAnalysis->getAttributes() as $element) { + $fullname = AttributeAnalyzer::determineAttributeFullyQualifiedName($tokens, $element['name'], $element['start']); + + if (!\in_array($fullname, $this->configuration['attributes'], true)) { + continue; + } + + $tokens->clearRange($element['start'], $element['end']); + ++$removedCount; + + $siblingIndex = $tokens->getNonEmptySibling($element['end'], 1); + + // Clear element comma + if (',' === $tokens[$siblingIndex]->getContent()) { + $tokens->clearAt($siblingIndex); + } + } + + // Clear whole attribute if all are removed (multiline attribute case) + if (\count($attributeAnalysis->getAttributes()) === $removedCount) { + $tokens->clearRange($attributeAnalysis->getStartIndex(), $attributeAnalysis->getEndIndex()); + } + + // Clear trailing comma + $tokenIndex = $tokens->getMeaningfulTokenSibling($attributeAnalysis->getClosingBracketIndex(), -1); + if (',' === $tokens[$tokenIndex]->getContent()) { + $tokens->clearAt($tokenIndex); + } + + $index = $endIndex; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('attributes', 'List of FQNs of attributes for removal.')) + ->setAllowedTypes(['class-string[]']) + ->setDefault([]) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/OrderedAttributesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/OrderedAttributesFixer.php new file mode 100644 index 0000000..2132760 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/AttributeNotation/OrderedAttributesFixer.php @@ -0,0 +1,273 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\AttributeNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-import-type _AttributeItems from AttributeAnalysis + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * order?: list, + * sort_algorithm?: 'alpha'|'custom', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * order: array, + * sort_algorithm: 'alpha'|'custom', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author HypeMC + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedAttributesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public const ORDER_ALPHA = 'alpha'; + public const ORDER_CUSTOM = 'custom'; + + private const SUPPORTED_SORT_ALGORITHMS = [ + self::ORDER_ALPHA, + self::ORDER_CUSTOM, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Sorts attributes using the configured sort algorithm.', + [ + new VersionSpecificCodeSample( + <<<'EOL' + self::ORDER_CUSTOM, 'order' => ['A\B\Qux', 'A\B\Bar', 'A\B\Corge']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after FullyQualifiedStrictTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $fixerName = $this->getName(); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'How the attributes should be sorted.')) + ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) + ->setDefault(self::ORDER_ALPHA) + ->setNormalizer(static function (Options $options, string $value) use ($fixerName): string { + if (self::ORDER_CUSTOM === $value && [] === $options['order']) { + throw new InvalidFixerConfigurationException( + $fixerName, + 'The custom order strategy requires providing `order` option with a list of attributes\'s FQNs.', + ); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('order', 'A list of FQCNs of attributes defining the desired order used when custom sorting algorithm is configured.')) + ->setAllowedTypes(['string[]']) + ->setDefault([]) + ->setNormalizer(static function (Options $options, array $value) use ($fixerName): array { + if ($value !== array_unique($value)) { + throw new InvalidFixerConfigurationException($fixerName, 'The list includes attributes that are not unique.'); + } + + return array_flip(array_values( + array_map(static fn (string $attribute): string => ltrim($attribute, '\\'), $value), + )); + }) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); + + $index = 0; + + while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) { + /** @var _AttributeItems $elements */ + $elements = array_map(fn (AttributeAnalysis $attributeAnalysis): array => [ + 'name' => $this->sortAttributes($fullyQualifiedNameAnalyzer, $tokens, $attributeAnalysis->getStartIndex(), $attributeAnalysis->getAttributes()), + 'start' => $attributeAnalysis->getStartIndex(), + 'end' => $attributeAnalysis->getEndIndex(), + ], AttributeAnalyzer::collect($tokens, $index)); + + $endIndex = end($elements)['end']; + + try { + if (1 === \count($elements)) { + continue; + } + + $sortedElements = $this->sortElements($elements); + + if ($elements === $sortedElements) { + continue; + } + + $this->sortTokens($tokens, $index, $endIndex, $sortedElements); + } finally { + $index = $endIndex; + } + } + } + + /** + * @param _AttributeItems $attributes + */ + private function sortAttributes(FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, Tokens $tokens, int $index, array $attributes): string + { + if (1 === \count($attributes)) { + return $this->getAttributeName($fullyQualifiedNameAnalyzer, $attributes[0]['name'], $attributes[0]['start']); + } + + foreach ($attributes as &$attribute) { + $attribute['name'] = $this->getAttributeName($fullyQualifiedNameAnalyzer, $attribute['name'], $attribute['start']); + } + + $sortedElements = $this->sortElements($attributes); + + if ($attributes === $sortedElements) { + return $attributes[0]['name']; + } + + $this->sortTokens($tokens, $index + 1, end($attributes)['end'], $sortedElements, new Token(',')); + + return $sortedElements[0]['name']; + } + + private function getAttributeName(FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, string $name, int $index): string + { + if (self::ORDER_CUSTOM === $this->configuration['sort_algorithm']) { + return $fullyQualifiedNameAnalyzer->getFullyQualifiedName($name, $index, NamespaceUseAnalysis::TYPE_CLASS); + } + + return ltrim($name, '\\'); + } + + /** + * @param _AttributeItems $elements + * + * @return _AttributeItems + */ + private function sortElements(array $elements): array + { + usort($elements, function (array $a, array $b): int { + $sortAlgorithm = $this->configuration['sort_algorithm']; + + if (self::ORDER_ALPHA === $sortAlgorithm) { + return $a['name'] <=> $b['name']; + } + + return + ($this->configuration['order'][$a['name']] ?? \PHP_INT_MAX) + <=> ($this->configuration['order'][$b['name']] ?? \PHP_INT_MAX); + }); + + return $elements; + } + + /** + * @param _AttributeItems $elements + */ + private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements, ?Token $delimiter = null): void + { + $replaceTokens = []; + + foreach ($elements as $pos => $element) { + for ($i = $element['start']; $i <= $element['end']; ++$i) { + $replaceTokens[] = clone $tokens[$i]; + } + if (null !== $delimiter && $pos !== \count($elements) - 1) { + $replaceTokens[] = clone $delimiter; + } + } + + $tokens->overrideRange($startIndex, $endIndex, $replaceTokens); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php new file mode 100644 index 0000000..21383ac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php @@ -0,0 +1,276 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureBracesFixer; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureContinuationPositionFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer; +use PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer; +use PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer; +use PhpCsFixer\Fixer\Whitespace\StatementIndentationFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Fixer for rules defined in PSR2 ¶4.1, ¶4.4, ¶5. + * + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * allow_single_line_anonymous_class_with_empty_body?: bool, + * allow_single_line_closure?: bool, + * position_after_anonymous_constructs?: 'next'|'same', + * position_after_control_structures?: 'next'|'same', + * position_after_functions_and_oop_constructs?: 'next'|'same', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * allow_single_line_anonymous_class_with_empty_body: bool, + * allow_single_line_closure: bool, + * position_after_anonymous_constructs: 'next'|'same', + * position_after_control_structures: 'next'|'same', + * position_after_functions_and_oop_constructs: 'next'|'same', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const LINE_NEXT = 'next'; + + /** + * @internal + */ + public const LINE_SAME = 'same'; + + private ?BracesPositionFixer $bracesPositionFixer = null; + + private ?ControlStructureContinuationPositionFixer $controlStructureContinuationPositionFixer = null; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.', + [ + new CodeSample( + <<<'PHP' + = 0; }; + $negative = function ($item) { + return $item < 0; }; + + PHP, + ['allow_single_line_closure' => true], + ), + new CodeSample( + <<<'PHP' + self::LINE_SAME], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocIndentationFixer. + * Must run after ClassAttributesSeparationFixer, ClassDefinitionFixer, EmptyLoopBodyFixer, NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUselessElseFixer, SingleLineThrowFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority(): int + { + return 35; + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + protected function configurePostNormalisation(): void + { + $this->getBracesPositionFixer()->configure([ + 'control_structures_opening_brace' => $this->translatePositionOption($this->configuration['position_after_control_structures']), + 'functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), + 'anonymous_functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), + 'classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), + 'anonymous_classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), + 'allow_single_line_empty_anonymous_classes' => $this->configuration['allow_single_line_anonymous_class_with_empty_body'], + 'allow_single_line_anonymous_functions' => $this->configuration['allow_single_line_closure'], + ]); + + $this->getControlStructureContinuationPositionFixer()->configure([ + 'position' => self::LINE_NEXT === $this->configuration['position_after_control_structures'] + ? ControlStructureContinuationPositionFixer::NEXT_LINE + : ControlStructureContinuationPositionFixer::SAME_LINE, + ]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('allow_single_line_anonymous_class_with_empty_body', 'Whether single line anonymous class with empty body notation should be allowed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'Whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_NEXT) + ->getOption(), + (new FixerOptionBuilder('position_after_control_structures', 'Whether the opening brace should be placed on "next" or "same" line after control structures.')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_SAME) + ->getOption(), + (new FixerOptionBuilder('position_after_anonymous_constructs', 'Whether the opening brace should be placed on "next" or "same" line after anonymous constructs (anonymous classes and lambda functions).')) + ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) + ->setDefault(self::LINE_SAME) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + $singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); + $singleSpaceAroundConstructFixer->configure([ + 'constructs_contain_a_single_space' => [], + 'constructs_followed_by_a_single_space' => ['elseif', 'for', 'foreach', 'if', 'match', 'while', 'use_lambda'], + 'constructs_preceded_by_a_single_space' => ['use_lambda'], + ]); + + $noExtraBlankLinesFixer = new NoExtraBlankLinesFixer(); + $noExtraBlankLinesFixer->configure([ + 'tokens' => ['curly_brace_block'], + ]); + + return [ + $singleSpaceAroundConstructFixer, + new ControlStructureBracesFixer(), + $noExtraBlankLinesFixer, + $this->getBracesPositionFixer(), + $this->getControlStructureContinuationPositionFixer(), + new DeclareParenthesesFixer(), + new NoMultipleStatementsPerLineFixer(), + new StatementIndentationFixer(true), + ]; + } + + private function getBracesPositionFixer(): BracesPositionFixer + { + if (null === $this->bracesPositionFixer) { + $this->bracesPositionFixer = new BracesPositionFixer(); + } + + return $this->bracesPositionFixer; + } + + private function getControlStructureContinuationPositionFixer(): ControlStructureContinuationPositionFixer + { + if (null === $this->controlStructureContinuationPositionFixer) { + $this->controlStructureContinuationPositionFixer = new ControlStructureContinuationPositionFixer(); + } + + return $this->controlStructureContinuationPositionFixer; + } + + /** + * @return BracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END|BracesPositionFixer::SAME_LINE + */ + private function translatePositionOption(string $option): string + { + return self::LINE_NEXT === $option + ? BracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END + : BracesPositionFixer::SAME_LINE; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php new file mode 100644 index 0000000..3e2a70f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesPositionFixer.php @@ -0,0 +1,504 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * allow_single_line_anonymous_functions?: bool, + * allow_single_line_empty_anonymous_classes?: bool, + * anonymous_classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * anonymous_functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * control_structures_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * allow_single_line_anonymous_functions: bool, + * allow_single_line_empty_anonymous_classes: bool, + * anonymous_classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * anonymous_functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * control_structures_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BracesPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + use IndentationTrait; + + /** + * @internal + */ + public const NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END = 'next_line_unless_newline_at_signature_end'; + + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + + private const CONTROL_STRUCTURE_TOKENS = [\T_DECLARE, \T_DO, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_FOR, \T_FOREACH, \T_IF, \T_WHILE, \T_TRY, \T_CATCH, \T_SWITCH, FCT::T_MATCH]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Braces must be placed as configured.', + [ + new CodeSample( + <<<'PHP' + self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], + ), + new CodeSample( + <<<'PHP' + self::SAME_LINE], + ), + new CodeSample( + <<<'PHP' + self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], + ), + new CodeSample( + <<<'PHP' + self::SAME_LINE], + ), + new CodeSample( + <<<'PHP' + self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('{'); + } + + /** + * {@inheritdoc} + * + * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. + * Must run after ControlStructureBracesFixer, MultilinePromotedPropertiesFixer, NoMultipleStatementsPerLineFixer. + */ + public function getPriority(): int + { + return -2; + } + + /** @protected */ + public function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('control_structures_opening_brace', 'The position of the opening brace of control structures‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('functions_opening_brace', 'The position of the opening brace of functions‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) + ->getOption(), + (new FixerOptionBuilder('anonymous_functions_opening_brace', 'The position of the opening brace of anonymous functions‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('classes_opening_brace', 'The position of the opening brace of classes‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) + ->getOption(), + (new FixerOptionBuilder('anonymous_classes_opening_brace', 'The position of the opening brace of anonymous classes‘ body.')) + ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_empty_anonymous_classes', 'Allow anonymous classes to have opening and closing braces on the same line.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('allow_single_line_anonymous_functions', 'Allow anonymous functions to have opening and closing braces on the same line.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(false, true)) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $classyTokens = Token::getClassyTokenKinds(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $allowSingleLineUntil = null; + + foreach ($tokens as $index => $token) { + $allowSingleLine = false; + $allowSingleLineIfEmpty = false; + + if ($token->isGivenKind($classyTokens)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + + if ($tokensAnalyzer->isAnonymousClass($index)) { + $allowSingleLineIfEmpty = true === $this->configuration['allow_single_line_empty_anonymous_classes']; + $positionOption = 'anonymous_classes_opening_brace'; + } else { + $positionOption = 'classes_opening_brace'; + } + } elseif ($token->isGivenKind(\T_FUNCTION)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]]); + + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + if ($tokensAnalyzer->isLambda($index)) { + $allowSingleLine = true === $this->configuration['allow_single_line_anonymous_functions']; + $positionOption = 'anonymous_functions_opening_brace'; + } else { + $positionOption = 'functions_opening_brace'; + } + } elseif ($token->isGivenKind(self::CONTROL_STRUCTURE_TOKENS)) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + $positionOption = 'control_structures_opening_brace'; + } elseif ($token->isGivenKind(\T_VARIABLE)) { + // handle default value - explicitly skip array as default value + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextMeaningfulIndex]->equals('=')) { + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($nextMeaningfulIndex); + + if ($tokens[$nextMeaningfulIndex]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $nextMeaningfulIndex); + } elseif ($tokens[$nextMeaningfulIndex]->isGivenKind(\T_ARRAY)) { + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($nextMeaningfulIndex); + if ($tokens[$nextMeaningfulIndex]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextMeaningfulIndex); + } + } + } + + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';', '.', [CT::T_CURLY_CLOSE], [CT::T_PROPERTY_HOOK_BRACE_OPEN], [\T_ENCAPSED_AND_WHITESPACE], [\T_CLOSE_TAG]]); + + if (!$tokens[$openBraceIndex]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + continue; + } + + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $openBraceIndex); + if (!$tokens->isPartialCodeMultiline($openBraceIndex, $closeBraceIndex)) { + continue; + } + + $positionOption = 'control_structures_opening_brace'; + } elseif ($token->isGivenKind(\T_STRING)) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny(['}', ';', [CT::T_ATTRIBUTE_CLOSE], [CT::T_PROPERTY_HOOK_BRACE_OPEN]])) { + continue; + } + $allowSingleLine = true === $this->configuration['allow_single_line_anonymous_functions']; + $positionOption = 'control_structures_opening_brace'; + } else { + continue; + } + + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $openBraceIndex); + + $addNewlinesInsideBraces = true; + if ($allowSingleLine || $allowSingleLineIfEmpty || $index < $allowSingleLineUntil) { + $addNewlinesInsideBraces = false; + + for ($indexInsideBraces = $openBraceIndex + 1; $indexInsideBraces < $closeBraceIndex; ++$indexInsideBraces) { + $tokenInsideBraces = $tokens[$indexInsideBraces]; + + if ( + ($allowSingleLineIfEmpty && !$tokenInsideBraces->isWhitespace() && !$tokenInsideBraces->isComment()) + || ($tokenInsideBraces->isWhitespace() && Preg::match('/\R/', $tokenInsideBraces->getContent())) + ) { + $addNewlinesInsideBraces = true; + + break; + } + } + + if (!$addNewlinesInsideBraces && null === $allowSingleLineUntil) { + $allowSingleLineUntil = $closeBraceIndex; + } + } + + if ( + $addNewlinesInsideBraces + && !$this->isFollowedByNewLine($tokens, $openBraceIndex) + && !$this->hasCommentOnSameLine($tokens, $openBraceIndex) + && !$tokens[$tokens->getNextMeaningfulToken($openBraceIndex)]->isGivenKind(\T_CLOSE_TAG) + ) { + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, $whitespace)) { + ++$closeBraceIndex; + } + } + + $whitespace = ' '; + if (self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END === $this->configuration[$positionOption]) { + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); + + $previousTokenIndex = $openBraceIndex; + do { + $previousTokenIndex = $tokens->getPrevMeaningfulToken($previousTokenIndex); + } while ($tokens[$previousTokenIndex]->isGivenKind([CT::T_TYPE_COLON, CT::T_NULLABLE_TYPE, \T_STRING, \T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, \T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_CALLABLE, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])); + + if ($tokens[$previousTokenIndex]->equals(')')) { + if ($tokens[--$previousTokenIndex]->isComment()) { + --$previousTokenIndex; + } + if ( + $tokens[$previousTokenIndex]->isWhitespace() + && Preg::match('/\R/', $tokens[$previousTokenIndex]->getContent()) + ) { + $whitespace = ' '; + } + } + } + + $moveBraceToIndex = null; + + if (' ' === $whitespace) { + $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($openBraceIndex); + for ($indexBeforeOpenBrace = $openBraceIndex - 1; $indexBeforeOpenBrace > $previousMeaningfulIndex; --$indexBeforeOpenBrace) { + if (!$tokens[$indexBeforeOpenBrace]->isComment()) { + continue; + } + + $tokenBeforeOpenBrace = $tokens[--$indexBeforeOpenBrace]; + if ($tokenBeforeOpenBrace->isWhitespace()) { + $moveBraceToIndex = $indexBeforeOpenBrace; + } elseif ($indexBeforeOpenBrace === $previousMeaningfulIndex) { + $moveBraceToIndex = $previousMeaningfulIndex + 1; + } + } + } elseif (!$tokens[$openBraceIndex - 1]->isWhitespace() || !Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { + for ($indexAfterOpenBrace = $openBraceIndex + 1; $indexAfterOpenBrace < $closeBraceIndex; ++$indexAfterOpenBrace) { + if ($tokens[$indexAfterOpenBrace]->isWhitespace() && Preg::match('/\R/', $tokens[$indexAfterOpenBrace]->getContent())) { + break; + } + + if ($tokens[$indexAfterOpenBrace]->isComment() && !str_starts_with($tokens[$indexAfterOpenBrace]->getContent(), '/*')) { + $moveBraceToIndex = $indexAfterOpenBrace + 1; + } + } + } + + if (null !== $moveBraceToIndex) { + $movedToken = clone $tokens[$openBraceIndex]; + + $delta = $openBraceIndex < $moveBraceToIndex ? 1 : -1; + + if ($tokens[$openBraceIndex + $delta]->isWhitespace()) { + if (-1 === $delta && Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { + $content = Preg::replace('/^(\h*?\R)?\h*/', '', $tokens[$openBraceIndex + 1]->getContent()); + if ('' !== $content) { + $tokens[$openBraceIndex + 1] = new Token([\T_WHITESPACE, $content]); + } else { + $tokens->clearAt($openBraceIndex + 1); + } + } elseif ($tokens[$openBraceIndex - 1]->isWhitespace()) { + $tokens->clearAt($openBraceIndex - 1); + } + } + + for ($i = $openBraceIndex; $i !== $moveBraceToIndex; $i += $delta) { + $siblingToken = $tokens[$i + $delta]; + $tokens[$i] = $siblingToken; + } + + $tokens[$i] = $movedToken; + + if ($tokens[$openBraceIndex]->isWhitespace() && $tokens[$openBraceIndex + 1]->isWhitespace()) { + $tokens[$openBraceIndex] = new Token([ + \T_WHITESPACE, + $tokens[$openBraceIndex]->getContent().$tokens[$openBraceIndex + 1]->getContent(), + ]); + $tokens->clearAt($openBraceIndex + 1); + } + + $openBraceIndex = $moveBraceToIndex; + } + + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, $whitespace)) { + ++$closeBraceIndex; + if (null !== $allowSingleLineUntil) { + ++$allowSingleLineUntil; + } + } + + if ( + !$addNewlinesInsideBraces + || $tokens[$tokens->getPrevMeaningfulToken($closeBraceIndex)]->isGivenKind(\T_OPEN_TAG) + ) { + continue; + } + + $prevIndex = $closeBraceIndex - 1; + while ($tokens->isEmptyAt($prevIndex)) { + --$prevIndex; + } + + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isWhitespace() && Preg::match('/\R/', $prevToken->getContent())) { + continue; + } + + $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); + $tokens->ensureWhitespaceAtIndex($prevIndex, 1, $whitespace); + } + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + // return if next token is not opening parenthesis + if (!$nextToken->equals('(')) { + return $structureTokenIndex; + } + + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + } + + private function isFollowedByNewLine(Tokens $tokens, int $index): bool + { + for (++$index, $max = \count($tokens) - 1; $index < $max; ++$index) { + $token = $tokens[$index]; + if (!$token->isComment()) { + return $token->isWhitespace() && Preg::match('/\R/', $token->getContent()); + } + } + + return false; + } + + private function hasCommentOnSameLine(Tokens $tokens, int $index): bool + { + $token = $tokens[$index + 1]; + + if ($token->isWhitespace() && !Preg::match('/\R/', $token->getContent())) { + $token = $tokens[$index + 2]; + } + + return $token->isComment(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php new file mode 100644 index 0000000..1167e74 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * allow_single_line_anonymous_functions?: bool, + * allow_single_line_empty_anonymous_classes?: bool, + * anonymous_classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * anonymous_functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * control_structures_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * allow_single_line_anonymous_functions: bool, + * allow_single_line_empty_anonymous_classes: bool, + * anonymous_classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * anonymous_functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * control_structures_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CurlyBracesPositionFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + use IndentationTrait; + + private BracesPositionFixer $bracesPositionFixer; + + public function __construct() + { + $this->bracesPositionFixer = new BracesPositionFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->bracesPositionFixer->getDefinition(); + + return new FixerDefinition( + 'Curly braces must be placed as configured.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + /** + * {@inheritdoc} + * + * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. + * Must run after ControlStructureBracesFixer, NoMultipleStatementsPerLineFixer. + */ + public function getPriority(): int + { + return $this->bracesPositionFixer->getPriority(); + } + + public function getSuccessorsNames(): array + { + return [ + $this->bracesPositionFixer->getName(), + ]; + } + + /** + * @param _AutogeneratedInputConfiguration $configuration + */ + protected function configurePreNormalisation(array $configuration): void + { + $this->bracesPositionFixer->configure($configuration); + } + + protected function createProxyFixers(): array + { + return [ + $this->bracesPositionFixer, + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return $this->bracesPositionFixer->createConfigurationDefinition(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php new file mode 100644 index 0000000..6886447 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR1 ¶2.2. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EncodingFixer extends AbstractFixer +{ + private string $bom; + + public function __construct() + { + parent::__construct(); + + $this->bom = pack('CCC', 0xEF, 0xBB, 0xBF); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP code MUST use only UTF-8 without BOM (remove BOM).', + [ + new CodeSample( + <<bom}getContent(); + + if (str_starts_with($content, $this->bom)) { + $newContent = substr($content, 3); + + if ('' === $newContent) { + $tokens->clearAt(0); + } else { + $tokens[0] = new Token([$tokens[0]->getId(), $newContent]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php new file mode 100644 index 0000000..d46013f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.3 Lines: There must not be more than one statement per line. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoMultipleStatementsPerLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use IndentationTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must not be more than one statement per line.', + [new CodeSample("isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 1, $max = \count($tokens) - 1; $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FOR)) { + $index = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS, + $tokens->getNextTokenOfKind($index, ['(']), + ); + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $index = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PROPERTY_HOOK, + $index, + ); + + continue; + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + for ($nextIndex = $index + 1; $nextIndex < $max; ++$nextIndex) { + $token = $tokens[$nextIndex]; + + if ($token->isWhitespace() || $token->isComment()) { + if (Preg::match('/\R/', $token->getContent())) { + break; + } + + continue; + } + + if (!$token->equalsAny(['}', [\T_CLOSE_TAG], [\T_ENDIF], [\T_ENDFOR], [\T_ENDSWITCH], [\T_ENDWHILE], [\T_ENDFOREACH]])) { + $whitespaceIndex = $index; + do { + $token = $tokens[++$whitespaceIndex]; + } while ($token->isComment()); + + $newline = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); + + if ($tokens->ensureWhitespaceAtIndex($whitespaceIndex, 0, $newline)) { + ++$max; + } + } + + break; + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php new file mode 100644 index 0000000..09c2923 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php @@ -0,0 +1,170 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: list<'arguments'|'array'|'array_destructuring'|'group_import'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: list<'arguments'|'array'|'array_destructuring'|'group_import'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingCommaInSinglelineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'If a list of values separated by a comma is contained on a single line, then the last item MUST NOT have a trailing comma.', + [ + new CodeSample(" ['array_destructuring']]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return + $tokens->isTokenKindFound(',') + && $tokens->isAnyTokenKindsFound([')', CT::T_ARRAY_BRACKET_CLOSE, CT::T_DESTRUCTURING_BRACKET_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE]); + } + + /** + * {@inheritdoc} + * + * Must run after MethodArgumentSpaceFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $elements = ['arguments', 'array', 'array_destructuring', 'group_import']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Which elements to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($elements)]) + ->setDefault($elements) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->equals(')') && !$tokens[$index]->isGivenKind([CT::T_ARRAY_BRACKET_CLOSE, CT::T_DESTRUCTURING_BRACKET_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE])) { + continue; + } + + $commaIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$commaIndex]->equals(',')) { + continue; + } + + $block = Tokens::detectBlockType($tokens[$index]); + $blockOpenIndex = $tokens->findBlockStart($block['type'], $index); + + if ($tokens->isPartialCodeMultiline($blockOpenIndex, $index)) { + continue; + } + + if (!$this->shouldBeCleared($tokens, $blockOpenIndex)) { + continue; + } + + do { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($commaIndex); + } while ($tokens[$commaIndex]->equals(',')); + + $tokens->removeTrailingWhitespace($commaIndex); + } + } + + private function shouldBeCleared(Tokens $tokens, int $openIndex): bool + { + $elements = $this->configuration['elements']; + + if ($tokens[$openIndex]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + return \in_array('array', $elements, true); + } + + if ($tokens[$openIndex]->isGivenKind(CT::T_DESTRUCTURING_BRACKET_OPEN)) { + return \in_array('array_destructuring', $elements, true); + } + + if ($tokens[$openIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + return \in_array('group_import', $elements, true); + } + + $beforeOpen = $tokens->getPrevMeaningfulToken($openIndex); + + if ($tokens[$beforeOpen]->isGivenKind(\T_ARRAY)) { + return \in_array('array', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind(\T_LIST)) { + return \in_array('array_destructuring', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind([\T_UNSET, \T_ISSET, \T_VARIABLE, \T_CLASS])) { + return \in_array('arguments', $elements, true); + } + + if ($tokens[$beforeOpen]->isGivenKind(\T_STRING)) { + return !AttributeAnalyzer::isAttribute($tokens, $beforeOpen) && \in_array('arguments', $elements, true); + } + + if ($tokens[$beforeOpen]->equalsAny([')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_BRACE_CLOSE]])) { + $block = Tokens::detectBlockType($tokens[$beforeOpen]); + + return + ( + Tokens::BLOCK_TYPE_INDEX_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_INDEX_BRACKET === $block['type'] + || Tokens::BLOCK_TYPE_PARENTHESIS === $block['type'] + ) && \in_array('arguments', $elements, true); + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php new file mode 100644 index 0000000..c8d22c8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php @@ -0,0 +1,193 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Removes Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * use_escape_sequences_in_strings?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * use_escape_sequences_in_strings: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Ivan Boprzenkov + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NonPrintableCharacterFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var non-empty-list + */ + private const TOKENS = [ + \T_STRING_VARNAME, + \T_INLINE_HTML, + \T_VARIABLE, + \T_COMMENT, + \T_ENCAPSED_AND_WHITESPACE, + \T_CONSTANT_ENCAPSED_STRING, + \T_DOC_COMMENT, + ]; + + /** + * @var array + */ + private array $symbolsReplace; + + public function __construct() + { + parent::__construct(); + + $this->symbolsReplace = [ + pack('H*', 'e2808b') => ['', '200b'], // ZWSP U+200B + pack('H*', 'e28087') => [' ', '2007'], // FIGURE SPACE U+2007 + pack('H*', 'e280af') => [' ', '202f'], // NBSP U+202F + pack('H*', 'e281a0') => ['', '2060'], // WORD JOINER U+2060 + pack('H*', 'c2a0') => [' ', 'a0'], // NO-BREAK SPACE U+A0 + ]; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols.', + [ + new CodeSample( + ' false], + ), + ], + null, + 'Risky when strings contain intended invisible characters.', + ); + } + + public function isRisky(): bool + { + return true; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::TOKENS); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_escape_sequences_in_strings', 'Whether characters should be replaced with escape sequences in strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $replacements = []; + $escapeSequences = []; + + foreach ($this->symbolsReplace as $character => [$replacement, $codepoint]) { + $replacements[$character] = $replacement; + $escapeSequences[$character] = '\u{'.$codepoint.'}'; + } + + foreach ($tokens as $index => $token) { + $content = $token->getContent(); + + if ( + true === $this->configuration['use_escape_sequences_in_strings'] + && $token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE]) + ) { + if (!Preg::match('/'.implode('|', array_keys($escapeSequences)).'/', $content)) { + continue; + } + + $previousToken = $tokens[$index - 1]; + $stringTypeChanged = false; + $swapQuotes = false; + + if ($previousToken->isGivenKind(\T_START_HEREDOC)) { + $previousTokenContent = $previousToken->getContent(); + + if (str_contains($previousTokenContent, '\'')) { + $tokens[$index - 1] = new Token([\T_START_HEREDOC, str_replace('\'', '', $previousTokenContent)]); + $stringTypeChanged = true; + } + } elseif (str_starts_with($content, "'")) { + $stringTypeChanged = true; + $swapQuotes = true; + } + + if ($swapQuotes) { + $content = str_replace("\\'", "'", $content); + } + + if ($stringTypeChanged) { + $content = Preg::replace('/(\\\{1,2})/', '\\\\\\\\', $content); + $content = str_replace('$', '\$', $content); + } + + if ($swapQuotes) { + $content = str_replace('"', '\"', $content); + $content = Preg::replace('/^\'(.*)\'$/s', '"$1"', $content); + } + + $tokens[$index] = new Token([$token->getId(), strtr($content, $escapeSequences)]); + + continue; + } + + if ($token->isGivenKind(self::TOKENS)) { + $newContent = strtr($content, $replacements); + + // variable name cannot contain space + if ($token->isGivenKind([\T_STRING_VARNAME, \T_VARIABLE]) && str_contains($newContent, ' ')) { + continue; + } + + // multiline comment must have "*/" only at the end + if ($token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT]) && str_starts_with($newContent, '/*') && strpos($newContent, '*/') !== \strlen($newContent) - 2) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NumericLiteralSeparatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NumericLiteralSeparatorFixer.php new file mode 100644 index 0000000..cc2ebe4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NumericLiteralSeparatorFixer.php @@ -0,0 +1,232 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Let's you add underscores to numeric literals. + * + * Inspired by: + * - {@link https://github.com/kubawerlos/php-cs-fixer-custom-fixers/blob/main/src/Fixer/NumericLiteralSeparatorFixer.php} + * - {@link https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/rules/numeric-separators-style.js} + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * override_existing?: bool, + * strategy?: 'no_separator'|'use_separator', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * override_existing: bool, + * strategy: 'no_separator'|'use_separator', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Marvin Heilemann + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NumericLiteralSeparatorFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public const STRATEGY_USE_SEPARATOR = 'use_separator'; + public const STRATEGY_NO_SEPARATOR = 'no_separator'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds separators to numeric literals of any kind.', + [ + new CodeSample( + <<<'PHP' + self::STRATEGY_NO_SEPARATOR], + ), + new CodeSample( + <<<'PHP' + self::STRATEGY_USE_SEPARATOR], + ), + new CodeSample( + " true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_DNUMBER, \T_LNUMBER]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'override_existing', + 'Whether literals already containing underscores should be reformatted.', + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'strategy', + 'Whether numeric literal should be separated by underscores or not.', + )) + ->setAllowedValues([self::STRATEGY_USE_SEPARATOR, self::STRATEGY_NO_SEPARATOR]) + ->setDefault(self::STRATEGY_USE_SEPARATOR) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind([\T_DNUMBER, \T_LNUMBER])) { + continue; + } + + $content = $token->getContent(); + + $newContent = $this->formatValue($content); + + if ($content === $newContent) { + // Skip Token override if its the same content, like when it + // already got a valid literal separator structure. + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } + + private function formatValue(string $value): string + { + if (self::STRATEGY_NO_SEPARATOR === $this->configuration['strategy']) { + return str_contains($value, '_') ? str_replace('_', '', $value) : $value; + } + + if (true === $this->configuration['override_existing']) { + $value = str_replace('_', '', $value); + } elseif (str_contains($value, '_')) { + // Keep already underscored literals untouched. + return $value; + } + + $lowerValue = strtolower($value); + + if (str_starts_with($lowerValue, '0b')) { + // Binary + return $this->insertEveryRight($value, 8, 2); + } + + if (str_starts_with($lowerValue, '0x')) { + // Hexadecimal + return $this->insertEveryRight($value, 2, 2); + } + + if (str_starts_with($lowerValue, '0o')) { + // Octal + return $this->insertEveryRight($value, 3, 2); + } + if (str_starts_with($lowerValue, '0') && !str_contains($lowerValue, '.')) { + // Octal notation prior PHP 8.1 but still valid + return $this->insertEveryRight($value, 3, 1); + } + + // All other types + + /** If its a negative value we need an offset */ + $negativeOffset = static fn (string $v): int => str_contains($v, '-') ? 1 : 0; + + Preg::matchAll('/([0-9-_]+)?((\.)([0-9_]*))?((e)([0-9-_]+))?/i', $value, $result); + \assert(isset($result[1][0], $result[3][0], $result[4][0], $result[6][0], $result[7][0])); + + $integer = $result[1][0]; + $joinedValue = $this->insertEveryRight($integer, 3, $negativeOffset($integer)); + + $dot = $result[3][0]; + if ('' !== $dot) { + $integer = $result[4][0]; + $decimal = $this->insertEveryLeft($integer, 3, $negativeOffset($integer)); + $joinedValue = $joinedValue.$dot.$decimal; + } + + $tim = $result[6][0]; + if ('' !== $tim) { + $integer = $result[7][0]; + $times = $this->insertEveryRight($integer, 3, $negativeOffset($integer)); + $joinedValue = $joinedValue.$tim.$times; + } + + return $joinedValue; + } + + private function insertEveryRight(string $value, int $length, int $offset = 0): string + { + $position = $length * -1; + while ($position > -(\strlen($value) - $offset)) { + $value = substr_replace($value, '_', $position, 0); + $position -= $length + 1; + } + + return $value; + } + + private function insertEveryLeft(string $value, int $length, int $offset = 0): string + { + $position = $length; + while ($position < \strlen($value)) { + $value = substr_replace($value, '_', $position, $offset); + $position += $length + 1; + } + + return $value; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php new file mode 100644 index 0000000..26ff26b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OctalNotationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Literal octal must be in `0o` notation.', + [ + new VersionSpecificCodeSample( + "= 8_01_00 && $tokens->isTokenKindFound(\T_LNUMBER); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_LNUMBER)) { + continue; + } + + $content = $token->getContent(); + + $newContent = Preg::replace('#^0_*+([0-7_]+)$#', '0o$1', $content); + + if ($content === $newContent) { + continue; + } + + $tokens[$index] = new Token([\T_LNUMBER, $newContent]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php new file mode 100644 index 0000000..1310933 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php @@ -0,0 +1,297 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * dir?: null|string, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * dir: null|string, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Jordi Boggiano + * @author Dariusz Rumiński + * @author Bram Gotink + * @author Graham Campbell + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PsrAutoloadingFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.', + [ + new FileSpecificCodeSample( + <<<'PHP' + './src'], + ), + ], + null, + 'This fixer may change your class name, which will break the code that depends on the old name.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before SelfAccessorFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function supports(\SplFileInfo $file): bool + { + if ($file instanceof StdinFileInfo) { + return false; + } + + if ( + // ignore file with extension other than php + ('php' !== $file->getExtension()) + // ignore file with name that cannot be a class name + || !Preg::match('/^'.TypeExpression::REGEX_IDENTIFIER.'$/', $file->getBasename('.php')) + ) { + return false; + } + + try { + $tokens = Tokens::fromCode(\sprintf('getBasename('.php'))); + + if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) { + // name cannot be a class name - detected by PHP 5.x + return false; + } + } catch (\ParseError $e) { + // name cannot be a class name - detected by PHP 7.x + return false; + } + + // ignore stubs/fixtures, since they typically contain invalid files for various reasons + return !Preg::match('{[/\\\](stub|fixture)s?[/\\\]}i', $file->getRealPath()); + } + + protected function configurePostNormalisation(): void + { + if (null !== $this->configuration['dir']) { + $realpath = realpath($this->configuration['dir']); + + if (false === $realpath) { + throw new \InvalidArgumentException(\sprintf('Failed to resolve configured directory "%s".', $this->configuration['dir'])); + } + + $this->configuration['dir'] = $realpath; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('dir', 'If provided, the directory where the project code is placed.')) + ->setAllowedTypes(['null', 'string']) + ->setDefault(null) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + + if (null !== $this->configuration['dir'] && !str_starts_with($file->getRealPath(), $this->configuration['dir'])) { + return; + } + + $namespace = null; + $namespaceStartIndex = null; + $namespaceEndIndex = null; + + $classyName = null; + $classyIndex = null; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_NAMESPACE)) { + if (null !== $namespace) { + return; + } + + $namespaceStartIndex = $tokens->getNextMeaningfulToken($index); + $namespaceEndIndex = $tokens->getNextTokenOfKind($namespaceStartIndex, [';']); + $namespace = trim($tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex - 1)); + } elseif ($token->isClassy()) { + if ($tokenAnalyzer->isAnonymousClass($index)) { + continue; + } + + if (null !== $classyName) { + return; + } + + $classyIndex = $tokens->getNextMeaningfulToken($index); + $classyName = $tokens[$classyIndex]->getContent(); + } + } + + if (null === $classyName) { + return; + } + + $expectedClassyName = $this->calculateClassyName($file, $namespace, $classyName); + + if ($classyName !== $expectedClassyName) { + $tokens[$classyIndex] = new Token([\T_STRING, $expectedClassyName]); + } + + if (null === $this->configuration['dir'] || null === $namespace) { + return; + } + + if (!is_dir($this->configuration['dir'])) { + return; + } + + $configuredDir = realpath($this->configuration['dir']); + $fileDir = \dirname($file->getRealPath()); + + if (\strlen($configuredDir) >= \strlen($fileDir)) { + return; + } + + $newNamespace = substr(str_replace('/', '\\', $fileDir), \strlen($configuredDir) + 1); + $originalNamespace = substr($namespace, -\strlen($newNamespace)); + + if ($originalNamespace !== $newNamespace && strtolower($originalNamespace) === strtolower($newNamespace)) { + $tokens->clearRange($namespaceStartIndex, $namespaceEndIndex); + $namespace = substr($namespace, 0, -\strlen($newNamespace)).$newNamespace; + + $newNamespace = Tokens::fromCode('clearRange(0, 2); + $newNamespace->clearEmptyTokens(); + + $tokens->insertAt($namespaceStartIndex, $newNamespace); + } + } + + private function calculateClassyName(\SplFileInfo $file, ?string $namespace, string $currentName): string + { + $name = $file->getBasename('.php'); + $maxNamespace = $this->calculateMaxNamespace($file, $namespace); + + if (null !== $this->configuration['dir']) { + return ('' !== $maxNamespace ? (str_replace('\\', '_', $maxNamespace).'_') : '').$name; + } + + $namespaceParts = array_reverse(explode('\\', $maxNamespace)); + + foreach ($namespaceParts as $namespacePart) { + $nameCandidate = \sprintf('%s_%s', $namespacePart, $name); + + if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) { + break; + } + + $name = $nameCandidate; + } + + return $name; + } + + private function calculateMaxNamespace(\SplFileInfo $file, ?string $namespace): string + { + if (null === $this->configuration['dir']) { + $root = \dirname($file->getRealPath()); + + while ($root !== \dirname($root)) { + $root = \dirname($root); + } + } else { + $root = realpath($this->configuration['dir']); + } + + $namespaceAccordingToFileLocation = trim(str_replace(\DIRECTORY_SEPARATOR, '\\', substr(\dirname($file->getRealPath()), \strlen($root))), '\\'); + + if (null === $namespace) { + return $namespaceAccordingToFileLocation; + } + + $namespaceAccordingToFileLocationPartsReversed = array_reverse(explode('\\', $namespaceAccordingToFileLocation)); + $namespacePartsReversed = array_reverse(explode('\\', $namespace)); + + foreach ($namespacePartsReversed as $key => $namespaceParte) { + if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) { + break; + } + + if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) { + break; + } + + unset($namespaceAccordingToFileLocationPartsReversed[$key]); + } + + return implode('\\', array_reverse($namespaceAccordingToFileLocationPartsReversed)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php new file mode 100644 index 0000000..8e0bd6b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleLineEmptyBodyFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty body of class, interface, trait, enum or function must be abbreviated as `{}` and placed on the same line as the previous symbol, separated by a single space.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_INTERFACE, \T_CLASS, \T_FUNCTION, \T_TRAIT, FCT::T_ENUM]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind([...Token::getClassyTokenKinds(), \T_FUNCTION])) { + continue; + } + + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + + $closeBraceIndex = $tokens->getNextNonWhitespace($openBraceIndex); + if (!$tokens[$closeBraceIndex]->equals('}')) { + continue; + } + + $tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, ''); + + $beforeOpenBraceIndex = $tokens->getPrevNonWhitespace($openBraceIndex); + if (!$tokens[$beforeOpenBraceIndex]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { + $tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, ' '); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php new file mode 100644 index 0000000..ddc5b38 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php @@ -0,0 +1,166 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassReferenceNameCasingFixer extends AbstractFixer +{ + private const NOT_BEFORE_KINDS = [ + CT::T_USE_TRAIT, + \T_AS, + \T_CASE, // PHP 8.1 trait enum-case + \T_CLASS, + \T_CONST, + \T_DOUBLE_ARROW, + \T_DOUBLE_COLON, + \T_FUNCTION, + \T_INTERFACE, + \T_OBJECT_OPERATOR, + \T_TRAIT, + FCT::T_NULLSAFE_OBJECT_OPERATOR, + FCT::T_ENUM, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When referencing an internal class it must be written using the correct casing.', + [ + new CodeSample("isTokenKindFound(\T_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $classNames = $this->getClassNames(); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $uses = []; + + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) { + $uses[strtolower($use->getShortName())] = true; + } + + foreach ($this->getClassReference($tokens, $namespace) as $reference) { + $currentContent = $tokens[$reference]->getContent(); + $lowerCurrentContent = strtolower($currentContent); + + if (isset($classNames[$lowerCurrentContent]) && $currentContent !== $classNames[$lowerCurrentContent] && !isset($uses[$lowerCurrentContent])) { + $tokens[$reference] = new Token([\T_STRING, $classNames[$lowerCurrentContent]]); + } + } + } + } + + /** + * @return iterable + */ + private function getClassReference(Tokens $tokens, NamespaceAnalysis $namespace): iterable + { + static $blockKinds; + + if (null === $blockKinds) { + $blockKinds = ['before' => [','], 'after' => [',']]; + + foreach (Tokens::getBlockEdgeDefinitions() as $definition) { + $blockKinds['before'][] = $definition['start']; + $blockKinds['after'][] = $definition['end']; + } + } + + $namespaceIsGlobal = $namespace->isGlobalNamespace(); + + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $nextIndex = $tokens->getNextMeaningfulToken($index); + + $isNamespaceSeparator = $tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR); + + if (!$isNamespaceSeparator && !$namespaceIsGlobal) { + continue; + } + + if ($isNamespaceSeparator) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevIndex]->isGivenKind(\T_STRING)) { + continue; + } + } elseif ($tokens[$prevIndex]->isGivenKind(self::NOT_BEFORE_KINDS)) { + continue; + } + + if ($tokens[$prevIndex]->equalsAny($blockKinds['before']) && $tokens[$nextIndex]->equalsAny($blockKinds['after'])) { + continue; + } + + if (!$tokens[$prevIndex]->isGivenKind(\T_NEW) && $tokens[$nextIndex]->equalsAny(['(', ';', '=', [\T_CLOSE_TAG]])) { + continue; + } + + yield $index; + } + } + + /** + * @return array + */ + private function getClassNames(): array + { + static $classes = null; + + if (null === $classes) { + $classes = []; + + foreach (get_declared_classes() as $class) { + if ((new \ReflectionClass($class))->isInternal()) { + $classes[strtolower($class)] = $class; + } + } + } + + return $classes; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php new file mode 100644 index 0000000..0c5895e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php @@ -0,0 +1,132 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for constants case. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case?: 'lower'|'upper', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case: 'lower'|'upper', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Pol Dellaiera + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ConstantCaseFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * Hold the function that will be used to convert the constants. + * + * @var callable + */ + private $fixFunction; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The PHP constants `true`, `false`, and `null` MUST be written using the correct casing.', + [ + new CodeSample(" 'upper']), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + protected function configurePostNormalisation(): void + { + if ('lower' === $this->configuration['case']) { + $this->fixFunction = static fn (string $content): string => strtolower($content); + } + + if ('upper' === $this->configuration['case']) { + $this->fixFunction = static fn (string $content): string => strtoupper($content); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case', 'Whether to use the `upper` or `lower` case syntax.')) + ->setAllowedValues(['upper', 'lower']) + ->setDefault('lower') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + static $forbiddenPrevKinds = null; + if (null === $forbiddenPrevKinds) { + $forbiddenPrevKinds = [ + \T_DOUBLE_COLON, + \T_EXTENDS, + \T_IMPLEMENTS, + \T_INSTANCEOF, + \T_NAMESPACE, + \T_NEW, + \T_NS_SEPARATOR, + ...Token::getObjectOperatorKinds(), + ]; + } + + foreach ($tokens as $index => $token) { + if (!$token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']], false)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind($forbiddenPrevKinds)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind([\T_PAAMAYIM_NEKUDOTAYIM, \T_NS_SEPARATOR]) || $tokens[$nextIndex]->equals('=', false)) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(\T_CASE) && $tokens[$nextIndex]->equals(';')) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), ($this->fixFunction)($token->getContent())]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php new file mode 100644 index 0000000..0d7644f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class IntegerLiteralCaseFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Integer literals must be in correct case.', + [ + new CodeSample( + "isTokenKindFound(\T_LNUMBER); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_LNUMBER)) { + continue; + } + + $content = $token->getContent(); + + $newContent = Preg::replaceCallback( + '#^0([boxBOX])([0-9a-fA-F_]+)$#', + // @phpstan-ignore-next-line offsetAccess.notFound + static fn (array $matches): string => '0'.strtolower($matches[1]).strtoupper($matches[2]), + $content, + ); + + if ($content === $newContent) { + continue; + } + + $tokens[$index] = new Token([\T_LNUMBER, $newContent]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php new file mode 100644 index 0000000..ca1f72d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.5. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LowercaseKeywordsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP keywords MUST be in lower case.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound(Token::getKeywords()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isKeyword() && !$token->isGivenKind(\T_HALT_COMPILER)) { + $tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php new file mode 100644 index 0000000..81fbe81 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php @@ -0,0 +1,132 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LowercaseStaticReferenceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class static references `self`, `static` and `parent` MUST be in lower case.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_STATIC, \T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny([[\T_STRING, 'self'], [\T_STATIC, 'static'], [\T_STRING, 'parent']], false)) { + continue; + } + + if (!self::isTokenToFix($tokens, $index)) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]); + } + } + + private static function isTokenToFix(Tokens $tokens, int $index): bool + { + if ($tokens[$index]->getContent() === strtolower($tokens[$index]->getContent())) { + return false; // case is already correct + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_DOUBLE_COLON)) { + return true; + } + if (!$tokens[$nextIndex]->isGivenKind([\T_VARIABLE, CT::T_TYPE_ALTERNATION]) && !$tokens[$nextIndex]->equalsAny(['(', ')', '{', ';'])) { + return false; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(\T_INSTANCEOF)) { + return true; + } + if ($tokens[$prevIndex]->isGivenKind(\T_CASE)) { + return !$tokens[$nextIndex]->equals(';'); + } + if (!$tokens[$prevIndex]->isGivenKind([\T_NEW, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, CT::T_TYPE_ALTERNATION]) && !$tokens[$prevIndex]->equalsAny(['(', '{'])) { + return false; + } + + if ($tokens[$prevIndex]->equals('(') && $tokens[$nextIndex]->equals(')')) { + return false; + } + + if ('static' === strtolower($tokens[$index]->getContent()) && $tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + return false; + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php new file mode 100644 index 0000000..35fabe8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MagicConstantCasingFixer extends AbstractFixer +{ + private const MAGIC_CONSTANTS = [ + \T_LINE => '__LINE__', + \T_FILE => '__FILE__', + \T_DIR => '__DIR__', + \T_FUNC_C => '__FUNCTION__', + \T_CLASS_C => '__CLASS__', + \T_METHOD_C => '__METHOD__', + \T_NS_C => '__NAMESPACE__', + CT::T_CLASS_CONSTANT => 'class', + \T_TRAIT_C => '__TRAIT__', + FCT::T_PROPERTY_C => '__PROPERTY__', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Magic constants should be referred to using the correct casing.', + [new CodeSample("isAnyTokenKindsFound($magicConstantTokenIds); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + $tokenId = $token->getId(); + + if (null === $tokenId || !isset(self::MAGIC_CONSTANTS[$tokenId])) { + continue; + } + + $tokens[$index] = new Token([$tokenId, self::MAGIC_CONSTANTS[$tokenId]]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php new file mode 100644 index 0000000..3de9a4c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php @@ -0,0 +1,209 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MagicMethodCasingFixer extends AbstractFixer +{ + /** + * @var array + */ + private const MAGIC_NAMES = [ + '__call' => '__call', + '__callstatic' => '__callStatic', + '__clone' => '__clone', + '__construct' => '__construct', + '__debuginfo' => '__debugInfo', + '__destruct' => '__destruct', + '__get' => '__get', + '__invoke' => '__invoke', + '__isset' => '__isset', + '__serialize' => '__serialize', + '__set' => '__set', + '__set_state' => '__set_state', + '__sleep' => '__sleep', + '__tostring' => '__toString', + '__unserialize' => '__unserialize', + '__unset' => '__unset', + '__wakeup' => '__wakeup', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Magic method definitions and calls must be using the correct casing.', + [ + new CodeSample( + <<<'PHP' + __INVOKE(1); + + PHP, + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_DOUBLE_COLON, ...Token::getObjectOperatorKinds()]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $inClass = 0; + $tokenCount = \count($tokens); + + for ($index = 1; $index < $tokenCount - 2; ++$index) { + if (0 === $inClass && $tokens[$index]->isClassy()) { + $inClass = 1; + $index = $tokens->getNextTokenOfKind($index, ['{']); + + continue; + } + + if (0 !== $inClass) { + if ($tokens[$index]->equals('{')) { + ++$inClass; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$inClass; + + continue; + } + } + + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; // wrong type + } + + $content = $tokens[$index]->getContent(); + + if (!str_starts_with($content, '__')) { + continue; // cheap look ahead + } + + $name = strtolower($content); + + if (!$this->isMagicMethodName($name)) { + continue; // method name is not one of the magic ones we can fix + } + + $nameInCorrectCasing = $this->getMagicMethodNameInCorrectCasing($name); + if ($nameInCorrectCasing === $content) { + continue; // method name is already in the correct casing, no fix needed + } + + if ($this->isFunctionSignature($tokens, $index)) { + if (0 !== $inClass) { + // this is a method definition we want to fix + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + } + + continue; + } + + if ($this->isMethodCall($tokens, $index)) { + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + + continue; + } + + if ( + ('__callstatic' === $name || '__set_state' === $name) + && $this->isStaticMethodCall($tokens, $index) + ) { + $this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing); + } + } + } + + private function isFunctionSignature(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) { + return false; // not a method signature + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + private function isMethodCall(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isObjectOperator()) { + return false; // not a "simple" method call + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + private function isStaticMethodCall(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(\T_DOUBLE_COLON)) { + return false; // not a "simple" static method call + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + /** + * @phpstan-assert-if-true key-of $name + */ + private function isMagicMethodName(string $name): bool + { + return isset(self::MAGIC_NAMES[$name]); + } + + /** + * @param key-of $name name of a magic method + * + * @return value-of + */ + private function getMagicMethodNameInCorrectCasing(string $name): string + { + return self::MAGIC_NAMES[$name]; + } + + private function setTokenToCorrectCasing(Tokens $tokens, int $index, string $nameInCorrectCasing): void + { + $tokens[$index] = new Token([\T_STRING, $nameInCorrectCasing]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php new file mode 100644 index 0000000..d291715 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NativeFunctionCasingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Function defined by PHP should be called using the correct casing.', + [new CodeSample("isTokenKindFound(\T_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + static $nativeFunctionNames = null; + + if (null === $nativeFunctionNames) { + $nativeFunctionNames = $this->getNativeFunctionNames(); + } + + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + // test if we are at a function all + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + // test if the function call is to a native PHP function + $lower = strtolower($tokens[$index]->getContent()); + if (!\array_key_exists($lower, $nativeFunctionNames)) { + continue; + } + + $tokens[$index] = new Token([\T_STRING, $nativeFunctionNames[$lower]]); + } + } + + /** + * @return array + */ + private function getNativeFunctionNames(): array + { + $allFunctions = get_defined_functions(); + $functions = []; + foreach ($allFunctions['internal'] as $function) { + $functions[strtolower($function)] = $function; + } + + return $functions; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php new file mode 100644 index 0000000..70bd69b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated in favour of NativeTypeDeclarationCasingFixer + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NativeFunctionTypeDeclarationCasingFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Native type declarations for functions should use the correct case.', + [ + new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NativeTypeDeclarationCasingFixer(); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php new file mode 100644 index 0000000..505aff7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NativeTypeDeclarationCasingFixer extends AbstractFixer +{ + /** + * https://secure.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration. + * + * self PHP 5.0 + * array PHP 5.1 + * callable PHP 5.4 + * bool PHP 7.0 + * float PHP 7.0 + * int PHP 7.0 + * string PHP 7.0 + * iterable PHP 7.1 + * void PHP 7.1 + * object PHP 7.2 + * static PHP 8.0 (return type only) + * mixed PHP 8.0 + * false PHP 8.0 (union return type only) + * null PHP 8.0 (union return type only) + * never PHP 8.1 (return type only) + * true PHP 8.2 (standalone type: https://wiki.php.net/rfc/true-type) + * false PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * null PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * + * @var array + */ + private array $types; + + public function __construct() + { + parent::__construct(); + + $this->types = [ + 'array' => true, + 'bool' => true, + 'callable' => true, + 'float' => true, + 'int' => true, + 'iterable' => true, + 'object' => true, + 'parent' => true, + 'self' => true, + 'static' => true, + 'string' => true, + 'void' => true, + ]; + + if (\PHP_VERSION_ID >= 8_00_00) { + $this->types['false'] = true; + $this->types['mixed'] = true; + $this->types['null'] = true; + } + + if (\PHP_VERSION_ID >= 8_01_00) { + $this->types['never'] = true; + } + + if (\PHP_VERSION_ID >= 8_02_00) { + $this->types['true'] = true; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Native type declarations should be used in the correct case.', + [ + new CodeSample( + "isAnyTokenKindsFound(Token::getClassyTokenKinds()); + + return + $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]) + || ($classyFound && $tokens->isTokenKindFound(\T_STRING)) + || ( + \PHP_VERSION_ID >= 8_03_00 + && $tokens->isTokenKindFound(\T_CONST) + && $classyFound + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + $content = $token->getContent(); + $lowercaseContent = strtolower($content); + if ($content === $lowercaseContent) { + continue; + } + if (!isset($this->types[$lowercaseContent])) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals('=') || $tokens[$prevIndex]->isGivenKind([\T_CASE, \T_OBJECT_OPERATOR, \T_DOUBLE_COLON, \T_NS_SEPARATOR])) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->equals('=') || $tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + if ( + !$tokens[$prevIndex]->isGivenKind([\T_CONST, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_COLON]) + && !$tokens[$nextIndex]->isGivenKind([\T_VARIABLE, CT::T_TYPE_ALTERNATION]) + ) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $lowercaseContent]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php new file mode 100644 index 0000000..11dc1c5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * space?: 'none'|'single', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * space: 'none'|'single', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CastSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const INSIDE_CAST_SPACE_REPLACE_MAP = [ + ' ' => '', + "\t" => '', + "\n" => '', + "\r" => '', + "\0" => '', + "\x0B" => '', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A single space or none should be between cast and variable.', + [ + new CodeSample( + " 'single'], + ), + new CodeSample( + " 'none'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoShortBoolCastFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isCast()) { + continue; + } + + $tokens[$index] = new Token([ + $token->getId(), + strtr($token->getContent(), self::INSIDE_CAST_SPACE_REPLACE_MAP), + ]); + + if ('single' === $this->configuration['space']) { + // force single whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace(" \t")) { + // - if next token is whitespaces that contains only spaces and tabs - override next token with single space + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } elseif (!$tokens[$index + 1]->isWhitespace()) { + // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + continue; + } + + // force no whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply between cast and variable.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('single') + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php new file mode 100644 index 0000000..1059cf0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LowercaseCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast should be written in lower case.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isCast()) { + continue; + } + + $tokens[$index] = new Token([$tokens[$index]->getId(), strtolower($tokens[$index]->getContent())]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php new file mode 100644 index 0000000..de21bfc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ModernizeTypesCastingFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `intval`, `floatval`, `doubleval`, `strval` and `boolval` function calls with according type casting operator.', + [ + new CodeSample( + <<<'PHP' + [\T_INT_CAST, '(int)'], + 'floatval' => [\T_DOUBLE_CAST, '(float)'], + 'doubleval' => [\T_DOUBLE_CAST, '(float)'], + 'strval' => [\T_STRING_CAST, '(string)'], + 'boolval' => [\T_BOOL_CAST, '(bool)'], + ] as $functionIdentity => $newToken) { + $currIndex = 0; + + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + + // analysing cursor shift + $currIndex = $openParenthesis; + + // indicator that the function is overridden + if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis)) { + continue; + } + + $paramContentEnd = $closeParenthesis; + $commaCandidate = $tokens->getPrevMeaningfulToken($paramContentEnd); + + if ($tokens[$commaCandidate]->equals(',')) { + $tokens->removeTrailingWhitespace($commaCandidate); + $tokens->clearAt($commaCandidate); + $paramContentEnd = $commaCandidate; + } + + // check if something complex passed as an argument and preserve parentheses then + $countParamTokens = 0; + + for ($paramContentIndex = $openParenthesis + 1; $paramContentIndex < $paramContentEnd; ++$paramContentIndex) { + // not a space, means some sensible token + if (!$tokens[$paramContentIndex]->isGivenKind(\T_WHITESPACE)) { + ++$countParamTokens; + } + } + + $preserveParentheses = $countParamTokens > 1; + + $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesis); + $afterCloseParenthesisToken = $tokens[$afterCloseParenthesisIndex]; + $wrapInParentheses = $afterCloseParenthesisToken->equalsAny(['[', '{']) || $afterCloseParenthesisToken->isGivenKind(\T_POW); + + // analyse namespace specification (root one or none) and decide what to do + $prevTokenIndex = $tokens->getPrevMeaningfulToken($functionName); + + if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + // get rid of root namespace when it used + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + + // perform transformation + $replacementSequence = [ + new Token($newToken), + new Token([\T_WHITESPACE, ' ']), + ]; + + if ($wrapInParentheses) { + array_unshift($replacementSequence, new Token('(')); + } + + if (!$preserveParentheses) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($closeParenthesis); + $tokens->clearAt($closeParenthesis); + + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($openParenthesis); + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearAt($openParenthesis); + } else { + // we'll need to provide a space after a casting operator + $tokens->removeTrailingWhitespace($functionName); + } + + if ($wrapInParentheses) { + $tokens->insertAt($closeParenthesis, new Token(')')); + } + + $tokens->overrideRange($functionName, $functionName, $replacementSequence); + + // nested transformations support + $currIndex = $functionName; + } while (null !== $currIndex); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php new file mode 100644 index 0000000..ecba138 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoShortBoolCastFixer extends AbstractFixer +{ + /** + * {@inheritdoc} + * + * Must run before CastSpacesFixer. + */ + public function getPriority(): int + { + return -9; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Short cast `bool` using double exclamation mark should not be used.', + [new CodeSample("isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 1; --$index) { + if ($tokens[$index]->equals('!')) { + $index = $this->fixShortCast($tokens, $index); + } + } + } + + private function fixShortCast(Tokens $tokens, int $index): int + { + for ($i = $index - 1; $i > 1; --$i) { + if ($tokens[$i]->equals('!')) { + $this->fixShortCastToBoolCast($tokens, $i, $index); + + break; + } + + if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) { + break; + } + } + + return $i; + } + + private function fixShortCastToBoolCast(Tokens $tokens, int $start, int $end): void + { + for (; $start <= $end; ++$start) { + if ( + !$tokens[$start]->isComment() + && !($tokens[$start]->isWhitespace() && $tokens[$start - 1]->isComment()) + ) { + $tokens->clearAt($start); + } + } + + $tokens->insertAt($start, new Token([\T_BOOL_CAST, '(bool)'])); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php new file mode 100644 index 0000000..77741b8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnsetCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Variables must be set `null` instead of using `(unset)` casting.', + [new CodeSample("isTokenKindFound(\T_UNSET_CAST); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_UNSET_CAST)) { + $this->fixUnsetCast($tokens, $index); + } + } + } + + private function fixUnsetCast(Tokens $tokens, int $index): void + { + $assignmentIndex = $tokens->getPrevMeaningfulToken($index); + if (null === $assignmentIndex || !$tokens[$assignmentIndex]->equals('=')) { + return; + } + + $varIndex = $tokens->getNextMeaningfulToken($index); + if (null === $varIndex || !$tokens[$varIndex]->isGivenKind(\T_VARIABLE)) { + return; + } + + $afterVar = $tokens->getNextMeaningfulToken($varIndex); + if (null === $afterVar || !$tokens[$afterVar]->equalsAny([';', [\T_CLOSE_TAG]])) { + return; + } + + $nextIsWhiteSpace = $tokens[$assignmentIndex + 1]->isWhitespace(); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($varIndex); + + ++$assignmentIndex; + if (!$nextIsWhiteSpace) { + $tokens->insertAt($assignmentIndex, new Token([\T_WHITESPACE, ' '])); + } + + ++$assignmentIndex; + $tokens->insertAt($assignmentIndex, new Token([\T_STRING, 'null'])); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php new file mode 100644 index 0000000..3b00de5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ShortScalarCastFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`.', + [ + new CodeSample( + "isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isCast()) { + continue; + } + + $castFrom = trim(substr($tokens[$index]->getContent(), 1, -1)); + $castFromLowered = strtolower($castFrom); + + $castTo = [ + 'boolean' => 'bool', + 'integer' => 'int', + 'double' => 'float', + 'real' => 'float', + 'binary' => 'string', + ][$castFromLowered] ?? null; + + if (null === $castTo) { + continue; + } + + $tokens[$index] = new Token([ + $tokens[$index]->getId(), + str_replace($castFrom, $castTo, $tokens[$index]->getContent()), + ]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php new file mode 100644 index 0000000..d467a67 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php @@ -0,0 +1,586 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * Make sure there is one blank line above and below class elements. + * + * The exception is when an element is the first or last item in a 'classy'. + * + * @phpstan-type _Class array{ + * index: int, + * open: int, + * close: int, + * elements: non-empty-list<_Element> + * } + * @phpstan-type _Element array{token: Token, type: string, index: int, start: int, end: int} + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const SPACING_NONE = 'none'; + + /** + * @internal + */ + public const SPACING_ONE = 'one'; + + private const SPACING_ONLY_IF_META = 'only_if_meta'; + private const MODIFIER_TYPES = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_ABSTRACT, \T_FINAL, \T_STATIC, \T_STRING, \T_NS_SEPARATOR, \T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + /** + * @var array + */ + private array $classElementTypes = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class, trait and interface elements must be separated with one or none blank line.', + [ + new CodeSample( + <<<'PHP' + ['property' => self::SPACING_ONE]], + ), + new CodeSample( + <<<'PHP' + ['const' => self::SPACING_ONE]], + ), + new CodeSample( + <<<'PHP' + ['const' => self::SPACING_ONLY_IF_META]], + ), + new VersionSpecificCodeSample( + <<<'PHP' + ['property' => self::SPACING_ONLY_IF_META]], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer. + * Must run after ModifierKeywordsFixer, OrderedClassElementsFixer, PhpUnitDataProviderMethodOrderFixer, SingleClassElementPerStatementFixer. + */ + public function getPriority(): int + { + return 55; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function configurePostNormalisation(): void + { + $this->classElementTypes = []; // reset previous configuration + + foreach ($this->configuration['elements'] as $elementType => $spacing) { + $this->classElementTypes[$elementType] = $spacing; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->getElementsByClass($tokens) as $class) { + $elements = $class['elements']; + + if (isset($this->classElementTypes[$elements[0]['type']])) { + $this->fixSpaceBelowClassElement($tokens, $class); + } + + foreach ($elements as $index => $element) { + if (isset($this->classElementTypes[$element['type']])) { + $this->fixSpaceAboveClassElement($tokens, $class, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option): bool { + foreach ($option as $type => $spacing) { + $supportedTypes = ['const', 'method', 'property', 'trait_import', 'case']; + + if (!\in_array($type, $supportedTypes, true)) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected element type, expected any of %s, got "%s".', + Utils::naturalLanguageJoin($supportedTypes), + \gettype($type).'#'.$type, + ), + ); + } + + $supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META]; + + if (!\in_array($spacing, $supportedSpacings, true)) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected spacing for element type "%s", expected any of %s, got "%s".', + $spacing, + Utils::naturalLanguageJoin($supportedSpacings), + \is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing), + ), + ); + } + } + + return true; + }]) + ->setDefault([ + 'const' => self::SPACING_ONE, + 'method' => self::SPACING_ONE, + 'property' => self::SPACING_ONE, + 'trait_import' => self::SPACING_NONE, + 'case' => self::SPACING_NONE, + ]) + ->getOption(), + ]); + } + + /** + * Fix spacing above an element of a class, interface or trait. + * + * Deals with comments, PHPDocs and spaces above the element with respect to the position of the + * element within the class, interface or trait. + * + * @param _Class $class + */ + private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex): void + { + \assert(isset($class['elements'][$elementIndex])); + $element = $class['elements'][$elementIndex]; + $elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0; + $nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']); + + // element is directly after class open brace + if ($nonWhiteAbove === $class['open']) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + + return; + } + + // deal with comments above an element + if ($tokens[$nonWhiteAbove]->isGivenKind(\T_COMMENT)) { + // check if the comment belongs to the previous element + if ($elementAboveEnd === $nonWhiteAbove) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + + return; + } + + // more than one line break, always bring it back to 2 line breaks between the element start and what is above it + if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + + return; + } + + // there are 2 cases: + if ( + 1 === $element['start'] - $nonWhiteAbove + || $tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0 + || $tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0 + ) { + // 1. The comment is meant for the element (although not a PHPDoc), + // make sure there is one line break between the element and the comment... + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + // ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + + if ($nonWhiteAboveComment === $class['open']) { + if ($tokens[$nonWhiteAboveComment - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAboveComment - 1]->getContent(), "\n") > 0) { + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 1); + } + } else { + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 2); + } + } else { + // 2. The comment belongs to the code above the element, + // make sure there is a blank line above the element (i.e. 2 line breaks) + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + } + + return; + } + + // deal with element with a PHPDoc/attribute above it + if ($tokens[$nonWhiteAbove]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) { + // there should be one linebreak between the element and the attribute above it + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + + // make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2); + + return; + } + + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + } + + /** + * @param _Class $class + */ + private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex): int + { + \assert(isset($class['elements'][$elementIndex])); + $type = $class['elements'][$elementIndex]['type']; + \assert(isset($this->classElementTypes[$type])); + $spacing = $this->classElementTypes[$type]; + + if (self::SPACING_ONE === $spacing) { + return 2; + } + + if (self::SPACING_NONE === $spacing) { + \assert(isset($class['elements'][$elementIndex + 1])); + $aboveElement = $class['elements'][$elementIndex + 1]; + + if ($aboveElement['type'] !== $type) { + return 2; + } + + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']); + + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + + // self::SPACING_ONLY_IF_META === $spacing + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']); + + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + + /** + * @param _Class $class + */ + private function fixSpaceBelowClassElement(Tokens $tokens, array $class): void + { + $element = $class['elements'][0]; + + // if this is last element fix; fix to the class end `}` here if appropriate + if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) { + $this->correctLineBreaks($tokens, $element['end'], $class['close'], 1); + } + } + + private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + ++$startIndex; + $numbOfWhiteTokens = $endIndex - $startIndex; + + if (0 === $numbOfWhiteTokens) { + $tokens->insertAt($startIndex, new Token([\T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)])); + + return; + } + + $lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex); + + if ($reqLineCount === $lineBreakCount) { + return; + } + + if ($lineBreakCount < $reqLineCount) { + $tokens[$startIndex] = new Token([ + \T_WHITESPACE, + str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(), + ]); + + return; + } + + // $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time + if (1 === $numbOfWhiteTokens) { + $tokens[$startIndex] = new Token([ + \T_WHITESPACE, + Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount), + ]); + + return; + } + } + + private function getLineBreakCount(Tokens $tokens, int $startIndex, int $endIndex): int + { + $lineCount = 0; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + $lineCount += substr_count($tokens[$i]->getContent(), "\n"); + } + + return $lineCount; + } + + private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd): int + { + for ($i = $start; $i > $elementAboveEnd; --$i) { + if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i); + + continue; + } + + if ($tokens[$i]->isComment()) { + $start = $i; + + continue; + } + + if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) { + break; + } + } + + return $start; + } + + /** + * @return iterable<_Class> + */ + private function getElementsByClass(Tokens $tokens): iterable + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $class = null; + + foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) { + $element['index'] = $index; + + if (null === $class || $element['classIndex'] !== $class['index']) { + if (null !== $class) { + yield $class; + } + + $classIndex = $element['classIndex']; + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpen); + $class = [ + 'index' => $element['classIndex'], + 'open' => $classOpen, + 'close' => $classEnd, + 'elements' => [], + ]; + } + + unset($element['classIndex']); + $element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class['open'], $index); + $element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class['index'], $index, $element['type'], $tokensAnalyzer); + + $class['elements'][] = $element; // reset the key by design + } + + if (null !== $class) { + yield $class; + } + } + + /** + * including trailing single line comments if belonging to the class element. + */ + private function getFirstTokenIndexOfClassElement(Tokens $tokens, int $classOpen, int $elementIndex): int + { + $firstElementAttributeIndex = $elementIndex; + + do { + $nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex); + + if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind(self::MODIFIER_TYPES)) { + $firstElementAttributeIndex = $nonWhiteAbove; + } else { + break; + } + } while ($firstElementAttributeIndex > $classOpen); + + return $firstElementAttributeIndex; + } + + /** + * including trailing single line comments if belonging to the class element. + */ + private function getLastTokenIndexOfClassElement(Tokens $tokens, int $classIndex, int $elementIndex, string $elementType, TokensAnalyzer $tokensAnalyzer): int + { + // find last token of the element + if ('method' === $elementType && !$tokens[$classIndex]->isGivenKind(\T_INTERFACE)) { + $attributes = $tokensAnalyzer->getMethodAttributes($elementIndex); + + if (true === $attributes['abstract']) { + $elementEndIndex = $tokens->getNextTokenOfKind($elementIndex, [';']); + } else { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $tokens->getNextTokenOfKind($elementIndex, ['{'])); + } + } elseif ('trait_import' === $elementType) { + $elementEndIndex = $elementIndex; + + do { + $elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex); + } while ($tokens[$elementEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(',')); + + if (!$tokens[$elementEndIndex]->equals(';')) { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $tokens->getNextTokenOfKind($elementIndex, ['{'])); + } + } elseif ('property' === $elementType) { + $elementEndIndex = $tokens->getNextTokenOfKind($elementIndex, [';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]]); + + if ($tokens[$elementEndIndex]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $elementEndIndex); + } + } else { // 'const', enum-'case', 'promoted_property', or 'method' of an interface + $elementEndIndex = $tokens->getNextTokenOfKind($elementIndex, [';', '{']); + } + + $singleLineElement = true; + + for ($i = $elementIndex + 1; $i < $elementEndIndex; ++$i) { + if (str_contains($tokens[$i]->getContent(), "\n")) { + $singleLineElement = false; + + break; + } + } + + if ($singleLineElement) { + while (true) { + $nextToken = $tokens[$elementEndIndex + 1]; + + if (($nextToken->isComment() || $nextToken->isWhitespace()) && !str_contains($nextToken->getContent(), "\n")) { + ++$elementEndIndex; + } else { + break; + } + } + + if ($tokens[$elementEndIndex]->isWhitespace()) { + $elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex); + } + } + + return $elementEndIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php new file mode 100644 index 0000000..a959234 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php @@ -0,0 +1,564 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for part of the rules defined in PSR2 ¶4.1 Extends and Implements and PSR12 ¶8. Anonymous Classes. + * + * @phpstan-type _ClassReferenceInfo array{start: int, count: int, multiLine: bool} + * @phpstan-type _AutogeneratedInputConfiguration array{ + * inline_constructor_arguments?: bool, + * multi_line_extends_each_single_line?: bool, + * single_item_single_line?: bool, + * single_line?: bool, + * space_before_parenthesis?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * inline_constructor_arguments: bool, + * multi_line_extends_each_single_line: bool, + * single_item_single_line: bool, + * single_line: bool, + * space_before_parenthesis: bool, + * } + * @phpstan-type _ClassyDefinitionInfo array{ + * start: int, + * classy: int, + * open: int, + * extends: false|_ClassReferenceInfo, + * implements: false|_ClassReferenceInfo, + * anonymousClass: bool, + * final: false|int, + * abstract: false|int, + * readonly: false|int, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassDefinitionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Whitespace around the keywords of a class, trait, enum or interfaces definition should be one space.', + [ + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + " true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, SingleLineEmptyBodyFixer. + * Must run after NewWithBracesFixer, NewWithParenthesesFixer, StringableForToStringFixer. + */ + public function getPriority(): int + { + return 36; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // -4, one for count to index, 3 because min. of tokens for a classy location. + for ($index = $tokens->getSize() - 4; $index > 0; --$index) { + if ($tokens[$index]->isClassy()) { + $this->fixClassyDefinition($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('multi_line_extends_each_single_line', 'Whether definitions should be multiline.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('single_item_single_line', 'Whether definitions should be single line when including a single item.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('single_line', 'Whether definitions should be single line.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('space_before_parenthesis', 'Whether there should be a single space after the parenthesis of anonymous class (PSR12) or not.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('inline_constructor_arguments', 'Whether constructor argument list in anonymous classes should be single line.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @param int $classyIndex Class definition token start index + */ + private function fixClassyDefinition(Tokens $tokens, int $classyIndex): void + { + $classDefInfo = $this->getClassyDefinitionInfo($tokens, $classyIndex); + + // PSR2 4.1 Lists of implements MAY be split across multiple lines, where each subsequent line is indented once. + // When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line. + + if (false !== $classDefInfo['implements']) { + $classDefInfo['implements'] = $this->fixClassyDefinitionImplements( + $tokens, + $classDefInfo['open'], + $classDefInfo['implements'], + ); + } + + if (false !== $classDefInfo['extends']) { + $classDefInfo['extends'] = $this->fixClassyDefinitionExtends( + $tokens, + false === $classDefInfo['implements'] ? $classDefInfo['open'] : $classDefInfo['implements']['start'], + $classDefInfo['extends'], + ); + } + + // PSR2: class definition open curly brace must go on a new line. + // PSR12: anonymous class curly brace on same line if not multi line implements. + + $classDefInfo['open'] = $this->fixClassyDefinitionOpenSpacing($tokens, $classDefInfo); + + if (false !== $classDefInfo['implements']) { + $end = $classDefInfo['implements']['start']; + } elseif (false !== $classDefInfo['extends']) { + $end = $classDefInfo['extends']['start']; + } else { + $end = $tokens->getPrevNonWhitespace($classDefInfo['open']); + } + + if ($classDefInfo['anonymousClass'] && false === $this->configuration['inline_constructor_arguments']) { + if (!$tokens[$end]->equals(')')) { // anonymous class with `extends` and/or `implements` + $start = $tokens->getPrevMeaningfulToken($end); + $this->makeClassyDefinitionSingleLine($tokens, $start, $end); + $end = $start; + } + + if ($tokens[$end]->equals(')')) { // skip constructor arguments of anonymous class + $end = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $end); + } + } + + // 4.1 The extends and implements keywords MUST be declared on the same line as the class name. + $this->makeClassyDefinitionSingleLine($tokens, $classDefInfo['start'], $end); + + $this->sortClassModifiers($tokens, $classDefInfo); + } + + /** + * @param _ClassReferenceInfo $classExtendsInfo + * + * @return _ClassReferenceInfo + */ + private function fixClassyDefinitionExtends(Tokens $tokens, int $classOpenIndex, array $classExtendsInfo): array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + + if (true === $this->configuration['single_line'] || false === $classExtendsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = false; + } elseif (true === $this->configuration['single_item_single_line'] && 1 === $classExtendsInfo['count']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = false; + } elseif (true === $this->configuration['multi_line_extends_each_single_line'] && $classExtendsInfo['multiLine']) { + $this->makeClassyInheritancePartMultiLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = true; + } + + return $classExtendsInfo; + } + + /** + * @param _ClassReferenceInfo $classImplementsInfo + * + * @return _ClassReferenceInfo + */ + private function fixClassyDefinitionImplements(Tokens $tokens, int $classOpenIndex, array $classImplementsInfo): array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + + if (true === $this->configuration['single_line'] || false === $classImplementsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = false; + } elseif (true === $this->configuration['single_item_single_line'] && 1 === $classImplementsInfo['count']) { + $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = false; + } else { + $this->makeClassyInheritancePartMultiLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = true; + } + + return $classImplementsInfo; + } + + /** + * @param _ClassyDefinitionInfo $classDefInfo + */ + private function fixClassyDefinitionOpenSpacing(Tokens $tokens, array $classDefInfo): int + { + if ($classDefInfo['anonymousClass']) { + if (false !== $classDefInfo['implements']) { + $spacing = $classDefInfo['implements']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; + } elseif (false !== $classDefInfo['extends']) { + $spacing = $classDefInfo['extends']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' '; + } else { + $spacing = ' '; + } + } else { + $spacing = $this->whitespacesConfig->getLineEnding(); + } + + $openIndex = $tokens->getNextTokenOfKind($classDefInfo['classy'], ['{']); + + if (' ' !== $spacing && str_contains($tokens[$openIndex - 1]->getContent(), "\n")) { + return $openIndex; + } + + if ($tokens[$openIndex - 1]->isWhitespace()) { + if (' ' !== $spacing || !$tokens[$tokens->getPrevNonWhitespace($openIndex - 1)]->isComment()) { + $tokens[$openIndex - 1] = new Token([\T_WHITESPACE, $spacing]); + } + + return $openIndex; + } + + $tokens->insertAt($openIndex, new Token([\T_WHITESPACE, $spacing])); + + return $openIndex + 1; + } + + /** + * @return _ClassyDefinitionInfo + */ + private function getClassyDefinitionInfo(Tokens $tokens, int $classyIndex): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']); + $def = [ + 'classy' => $classyIndex, + 'open' => $openIndex, + 'extends' => false, + 'implements' => false, + 'anonymousClass' => false, + 'final' => false, + 'abstract' => false, + 'readonly' => false, + ]; + + if (!$tokens[$classyIndex]->isGivenKind(\T_TRAIT)) { + $extends = $tokens->findGivenKind(\T_EXTENDS, $classyIndex, $openIndex); + $def['extends'] = [] !== $extends ? $this->getClassyInheritanceInfo($tokens, array_key_first($extends)) : false; + + if (!$tokens[$classyIndex]->isGivenKind(\T_INTERFACE)) { + $implements = $tokens->findGivenKind(\T_IMPLEMENTS, $classyIndex, $openIndex); + $def['implements'] = [] !== $implements ? $this->getClassyInheritanceInfo($tokens, array_key_first($implements)) : false; + $def['anonymousClass'] = $tokensAnalyzer->isAnonymousClass($classyIndex); + } + } + + if ($def['anonymousClass']) { + $startIndex = $tokens->getPrevTokenOfKind($classyIndex, [[\T_NEW]]); // go to "new" for anonymous class + } else { + $modifiers = $tokensAnalyzer->getClassyModifiers($classyIndex); + $startIndex = $classyIndex; + + foreach (['final', 'abstract', 'readonly'] as $modifier) { + if (isset($modifiers[$modifier])) { + $def[$modifier] = $modifiers[$modifier]; + $startIndex = min($startIndex, $modifiers[$modifier]); + } else { + $def[$modifier] = false; + } + } + } + + $def['start'] = $startIndex; + + return $def; + } + + /** + * @return _ClassReferenceInfo + */ + private function getClassyInheritanceInfo(Tokens $tokens, int $startIndex): array + { + $implementsInfo = ['start' => $startIndex, 'count' => 1, 'multiLine' => false]; + ++$startIndex; + $endIndex = $tokens->getNextTokenOfKind($startIndex, ['{', [\T_IMPLEMENTS], [\T_EXTENDS]]); + $endIndex = $tokens[$endIndex]->equals('{') ? $tokens->getPrevNonWhitespace($endIndex) : $endIndex; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->equals(',')) { + ++$implementsInfo['count']; + + continue; + } + + if (!$implementsInfo['multiLine'] && str_contains($tokens[$i]->getContent(), "\n")) { + $implementsInfo['multiLine'] = true; + } + } + + return $implementsInfo; + } + + private function makeClassyDefinitionSingleLine(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex; $i >= $startIndex; --$i) { + if ($tokens[$i]->isWhitespace()) { + if (str_contains($tokens[$i]->getContent(), "\n")) { + if ($tokens[$i - 1]->isGivenKind(CT::T_ATTRIBUTE_CLOSE) || $tokens[$i + 1]->isGivenKind(FCT::T_ATTRIBUTE)) { + continue; + } + if (($tokens[$i - 1]->isComment() && str_ends_with($tokens[$i - 1]->getContent(), ']')) + || ($tokens[$i + 1]->isComment() && str_starts_with($tokens[$i + 1]->getContent(), '#[')) + ) { + continue; + } + + if ($tokens[$i - 1]->isGivenKind(\T_DOC_COMMENT) || $tokens[$i + 1]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + } + + if ($tokens[$i - 1]->isComment()) { + $content = $tokens[$i - 1]->getContent(); + if (!str_starts_with($content, '//') && !str_starts_with($content, '#')) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } + + continue; + } + + if ($tokens[$i + 1]->isComment()) { + $content = $tokens[$i + 1]->getContent(); + if (!str_starts_with($content, '//')) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } + + continue; + } + + if ($tokens[$i - 1]->isGivenKind(\T_CLASS) && $tokens[$i + 1]->equals('(')) { + if (true === $this->configuration['space_before_parenthesis']) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } else { + $tokens->clearAt($i); + } + + continue; + } + + if (!$tokens[$i - 1]->equals(',') && $tokens[$i + 1]->equalsAny([',', ')']) || $tokens[$i - 1]->equals('(')) { + $tokens->clearAt($i); + + continue; + } + + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + + continue; + } + + if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) { + $tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' '])); + + continue; + } + + if (true === $this->configuration['space_before_parenthesis'] && $tokens[$i]->isGivenKind(\T_CLASS) && !$tokens[$i + 1]->isWhitespace()) { + $tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' '])); + + continue; + } + + if (!$tokens[$i]->isComment()) { + continue; + } + + if (!$tokens[$i + 1]->isWhitespace() && !$tokens[$i + 1]->isComment() && !str_contains($tokens[$i]->getContent(), "\n")) { + $tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' '])); + } + + if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i - 1]->isComment()) { + $tokens->insertAt($i, new Token([\T_WHITESPACE, ' '])); + } + } + } + + private function makeClassyInheritancePartMultiLine(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex; $i > $startIndex; --$i) { + $previousInterfaceImplementingIndex = $tokens->getPrevTokenOfKind($i, [',', [\T_IMPLEMENTS], [\T_EXTENDS]]); + $breakAtIndex = $tokens->getNextMeaningfulToken($previousInterfaceImplementingIndex); + + // make the part of a ',' or 'implements' single line + $this->makeClassyDefinitionSingleLine( + $tokens, + $breakAtIndex, + $i, + ); + + // make sure the part is on its own line + $isOnOwnLine = false; + + for ($j = $breakAtIndex; $j > $previousInterfaceImplementingIndex; --$j) { + if (str_contains($tokens[$j]->getContent(), "\n")) { + $isOnOwnLine = true; + + break; + } + } + + if (!$isOnOwnLine) { + if ($tokens[$breakAtIndex - 1]->isWhitespace()) { + $tokens[$breakAtIndex - 1] = new Token([ + \T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent(), + ]); + } else { + $tokens->insertAt($breakAtIndex, new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent()])); + } + } + + $i = $previousInterfaceImplementingIndex + 1; + } + } + + /** + * @param _ClassyDefinitionInfo $classDefInfo + */ + private function sortClassModifiers(Tokens $tokens, array $classDefInfo): void + { + if (false === $classDefInfo['readonly']) { + return; + } + + $readonlyIndex = $classDefInfo['readonly']; + + foreach (['final', 'abstract'] as $accessModifier) { + if (false === $classDefInfo[$accessModifier] || $classDefInfo[$accessModifier] < $readonlyIndex) { + continue; + } + + $accessModifierIndex = $classDefInfo[$accessModifier]; + + $readonlyToken = clone $tokens[$readonlyIndex]; + $accessToken = clone $tokens[$accessModifierIndex]; + + $tokens[$readonlyIndex] = $accessToken; + $tokens[$accessModifierIndex] = $readonlyToken; + + break; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php new file mode 100644 index 0000000..c36159f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FinalClassFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All classes must be final, except abstract ones and Doctrine entities.', + [ + new CodeSample( + <<<'PHP' + configure([ + 'include' => [], + 'consider_absent_docblock_as_internal_class' => true, + ]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php new file mode 100644 index 0000000..c515fbf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php @@ -0,0 +1,372 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * annotation_exclude?: list, + * annotation_include?: list, + * consider_absent_docblock_as_internal_class?: bool, + * exclude?: list, + * include?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * annotation_exclude: array, + * annotation_include: array, + * consider_absent_docblock_as_internal_class: bool, + * exclude: array, + * include: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FinalInternalClassFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const DEFAULTS = [ + 'include' => [ + 'internal', + ], + 'exclude' => [ + 'final', + 'Entity', + 'ORM\Entity', + 'ORM\Mapping\Entity', + 'Mapping\Entity', + 'Document', + 'ODM\Document', + ], + ]; + private const CLASS_CANDIDATE_ACCEPT_TYPES = [ + CT::T_ATTRIBUTE_CLOSE, + \T_DOC_COMMENT, + \T_COMMENT, // Skip comments + FCT::T_READONLY, + ]; + + private bool $checkAttributes; + + public function __construct() + { + parent::__construct(); + + $this->checkAttributes = \PHP_VERSION_ID >= 8_00_00; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Internal classes should be `final`.', + [ + new CodeSample(" ['@Custom'], + 'exclude' => ['@not-fix'], + ], + ), + ], + null, + 'Changing classes to `final` might cause code execution to break.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before ProtectedToPrivateFixer, SelfStaticAccessorFixer. + * Must run after PhpUnitInternalClassFixer. + */ + public function getPriority(): int + { + return 67; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_CLASS); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->assertConfigHasNoConflicts(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->isClassCandidate($tokensAnalyzer, $tokens, $index)) { + continue; + } + + // make class 'final' + $tokens->insertSlices([ + $index => [ + new Token([\T_FINAL, 'final']), + new Token([\T_WHITESPACE, ' ']), + ], + ]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $annotationsAsserts = [static function (array $values): bool { + foreach ($values as $value) { + if ('' === $value) { + return false; + } + } + + return true; + }]; + + $annotationsNormalizer = static function (Options $options, array $value): array { + $newValue = []; + foreach ($value as $key) { + if (str_starts_with($key, '@')) { + $key = substr($key, 1); + } + + $newValue[strtolower($key)] = true; + } + + return $newValue; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotation_include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues($annotationsAsserts) + ->setDefault( + array_map( + static fn (string $string) => '@'.$string, + self::DEFAULTS['include'], + ), + ) + ->setNormalizer($annotationsNormalizer) + ->setDeprecationMessage('Use `include` to configure PHPDoc annotations tags and attributes.') + ->getOption(), + (new FixerOptionBuilder('annotation_exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues($annotationsAsserts) + ->setDefault( + array_map( + static fn (string $string) => '@'.$string, + self::DEFAULTS['exclude'], + ), + ) + ->setNormalizer($annotationsNormalizer) + ->setDeprecationMessage('Use `exclude` to configure PHPDoc annotations tags and attributes.') + ->getOption(), + (new FixerOptionBuilder('include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues($annotationsAsserts) + ->setDefault(self::DEFAULTS['include']) + ->setNormalizer($annotationsNormalizer) + ->getOption(), + (new FixerOptionBuilder('exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues($annotationsAsserts) + ->setDefault(self::DEFAULTS['exclude']) + ->setNormalizer($annotationsNormalizer) + ->getOption(), + (new FixerOptionBuilder('consider_absent_docblock_as_internal_class', 'Whether classes without any DocBlock should be fixed to final.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param int $index T_CLASS index + */ + private function isClassCandidate(TokensAnalyzer $tokensAnalyzer, Tokens $tokens, int $index): bool + { + if ($tokensAnalyzer->isAnonymousClass($index)) { + return false; + } + + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + + if (isset($modifiers['final']) || isset($modifiers['abstract'])) { + return false; // ignore class; it is abstract or already final + } + + $decisions = []; + $currentIndex = $index; + + while (null !== $currentIndex) { + $currentIndex = $tokens->getPrevNonWhitespace($currentIndex); + + if (!$tokens[$currentIndex]->isGivenKind(self::CLASS_CANDIDATE_ACCEPT_TYPES)) { + break; + } + + if ($this->checkAttributes && $tokens[$currentIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $attributeStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $currentIndex); + $decisions[] = $this->isClassCandidateBasedOnAttribute($tokens, $attributeStartIndex, $currentIndex); + + $currentIndex = $attributeStartIndex; + } + + if ($tokens[$currentIndex]->isGivenKind(\T_DOC_COMMENT)) { + $decisions[] = $this->isClassCandidateBasedOnPhpDoc($tokens, $currentIndex); + } + } + + if (\in_array(false, $decisions, true)) { + return false; + } + + return \in_array(true, $decisions, true) + || ([] === $decisions && true === $this->configuration['consider_absent_docblock_as_internal_class']); + } + + private function isClassCandidateBasedOnPhpDoc(Tokens $tokens, int $index): ?bool + { + $doc = new DocBlock($tokens[$index]->getContent()); + $tags = []; + + foreach ($doc->getAnnotations() as $annotation) { + if (!Preg::match('/@([^\(\s]+)/', $annotation->getContent(), $matches)) { + continue; + } + $tag = strtolower(substr(array_shift($matches), 1)); + + $tags[$tag] = true; + } + + if (\count(array_intersect_key($this->configuration['exclude'], $tags)) > 0) { + return false; + } + + if ($this->isConfiguredAsInclude($tags)) { + return true; + } + + return null; + } + + private function isClassCandidateBasedOnAttribute(Tokens $tokens, int $startIndex, int $endIndex): ?bool + { + $attributeCandidates = []; + $attributeString = ''; + $currentIndex = $startIndex; + + while ($currentIndex < $endIndex && null !== ($currentIndex = $tokens->getNextMeaningfulToken($currentIndex))) { + if (!$tokens[$currentIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + if ('' !== $attributeString) { + $attributeCandidates[$attributeString] = true; + $attributeString = ''; + } + + continue; + } + + $attributeString .= strtolower($tokens[$currentIndex]->getContent()); + } + + if (\count(array_intersect_key($this->configuration['exclude'], $attributeCandidates)) > 0) { + return false; + } + + if ($this->isConfiguredAsInclude($attributeCandidates)) { + return true; + } + + return null; + } + + /** + * @param array $attributes + */ + private function isConfiguredAsInclude(array $attributes): bool + { + if (0 === \count($this->configuration['include'])) { + return true; + } + + return \count(array_intersect_key($this->configuration['include'], $attributes)) > 0; + } + + private function assertConfigHasNoConflicts(): void + { + foreach (['include' => 'annotation_include', 'exclude' => 'annotation_exclude'] as $newConfigKey => $oldConfigKey) { + $defaults = []; + + foreach (self::DEFAULTS[$newConfigKey] as $foo) { + $defaults[strtolower($foo)] = true; + } + + $newConfigIsSet = $this->configuration[$newConfigKey] !== $defaults; + $oldConfigIsSet = $this->configuration[$oldConfigKey] !== $defaults; + + if ($newConfigIsSet && $oldConfigIsSet) { + throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Configuration cannot contain deprecated option "%s" and new option "%s".', $oldConfigKey, $newConfigKey)); + } + + if ($oldConfigIsSet) { + $this->configuration[$newConfigKey] = $this->configuration[$oldConfigKey]; // @phpstan-ignore-line crazy mapping, to be removed while cleaning up deprecated options + $this->checkAttributes = false; // run in old mode + } + + // if ($newConfigIsSet) - only new config is set, all good + // if (!$newConfigIsSet && !$oldConfigIsSet) - both are set as to default values, all good + + unset($this->configuration[$oldConfigKey]); // @phpstan-ignore-line crazy mapping, to be removed while cleaning up deprecated options + } + + $intersect = array_intersect_assoc($this->configuration['include'], $this->configuration['exclude']); + + if (\count($intersect) > 0) { + throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Annotation cannot be used in both "include" and "exclude" list, got duplicates: %s.', Utils::naturalLanguageJoin(array_keys($intersect)))); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php new file mode 100644 index 0000000..2db3fbe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FinalPublicMethodForAbstractClassFixer extends AbstractFixer +{ + /** + * @var array + */ + private array $magicMethods = [ + '__construct' => true, + '__destruct' => true, + '__call' => true, + '__callstatic' => true, + '__get' => true, + '__set' => true, + '__isset' => true, + '__unset' => true, + '__sleep' => true, + '__wakeup' => true, + '__tostring' => true, + '__invoke' => true, + '__set_state' => true, + '__clone' => true, + '__debuginfo' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All `public` methods of `abstract` classes should be `final`.', + [ + new CodeSample( + <<<'PHP' + isAllTokenKindsFound([\T_ABSTRACT, \T_PUBLIC, \T_FUNCTION]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $abstracts = array_keys($tokens->findGivenKind(\T_ABSTRACT)); + + foreach (array_reverse($abstracts) as $abstractIndex) { + $classIndex = $tokens->getNextTokenOfKind($abstractIndex, [[\T_CLASS], [\T_FUNCTION]]); + if (!$tokens[$classIndex]->isGivenKind(\T_CLASS)) { + continue; + } + + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpen); + + $this->fixClass($tokens, $classOpen, $classClose); + } + } + + private function fixClass(Tokens $tokens, int $classOpenIndex, int $classCloseIndex): void + { + for ($index = $classCloseIndex - 1; $index > $classOpenIndex; --$index) { + // skip method contents + if ($tokens[$index]->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + // skip non public methods + if (!$tokens[$index]->isGivenKind(\T_PUBLIC)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->isGivenKind(\T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + // skip uses, attributes, constants etc + if (!$nextToken->isGivenKind(\T_FUNCTION)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + + // skip magic methods + if (isset($this->magicMethods[strtolower($nextToken->getContent())])) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isGivenKind(\T_STATIC)) { + $index = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + } + + // skip abstract or already final methods + if ($prevToken->isGivenKind([\T_ABSTRACT, \T_FINAL])) { + $index = $prevIndex; + + continue; + } + + $tokens->insertAt( + $index, + [ + new Token([\T_FINAL, 'final']), + new Token([\T_WHITESPACE, ' ']), + ], + ); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModernSerializationMethodsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModernSerializationMethodsFixer.php new file mode 100644 index 0000000..b8e2780 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModernSerializationMethodsFixer.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @see https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_the_sleep_and_wakeup_magic_methods + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ModernSerializationMethodsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use new serialization methods `__serialize` and `__unserialize` instead of deprecated ones `__sleep` and `__wakeup`.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_CLASS, \T_FUNCTION]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $methodsByClass = []; + foreach ((new TokensAnalyzer($tokens))->getClassyElements() as $index => $element) { + if ('method' !== $element['type']) { + continue; + } + + if (!isset($methodsByClass[$element['classIndex']])) { + $methodsByClass[$element['classIndex']] = []; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + + $methodsByClass[$element['classIndex']][$functionName] = $functionNameIndex; + } + + $tokensToInsert = []; + foreach ($methodsByClass as $methods) { + if (isset($methods['__sleep']) && !isset($methods['__serialize'])) { + $tokens[$methods['__sleep']] = new Token([\T_STRING, '__serialize']); + } + + if (isset($methods['__wakeup']) && !isset($methods['__unserialize'])) { + $tokens[$methods['__wakeup']] = new Token([\T_STRING, '__unserialize']); + + $openParenthesisIndex = $tokens->getNextTokenOfKind($methods['__wakeup'], ['(']); + + $tokensToInsert[$openParenthesisIndex + 1] = [ + new Token([CT::T_ARRAY_TYPEHINT, 'array']), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_VARIABLE, '$data']), + ]; + } + } + if ([] !== $tokensToInsert) { + $tokens->insertSlices($tokensToInsert); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModifierKeywordsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModifierKeywordsFixer.php new file mode 100644 index 0000000..2823d98 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ModifierKeywordsFixer.php @@ -0,0 +1,320 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.5. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: list<'const'|'method'|'property'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: list<'const'|'method'|'property'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ModifierKeywordsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const PROPERTY_TYPE_DECLARATION_KINDS = [\T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + private const EXPECTED_KINDS_GENERIC = [\T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + private const EXPECTED_KINDS_PROPERTY_KINDS = [...self::EXPECTED_KINDS_GENERIC, ...self::PROPERTY_TYPE_DECLARATION_KINDS]; + + /** + * @var list<'const'|'method'|'promoted_property'|'property'> + */ + private array $elements = ['const', 'method', 'property']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Classes, constants, properties, and methods MUST have visibility declared, and keyword modifiers MUST be in the following order:' + .' inheritance modifier (`abstract` or `final`),' + .' visibility modifier (`public`, `protected`, or `private`),' + .' set-visibility modifier (`public(set)`, `protected(set)`, or `private(set)`),' + .' scope modifier (`static`),' + .' mutation modifier (`readonly`),' + .' type declaration, name.', + [ + new CodeSample( + <<<'PHP' + "a"; set; } + + readonly final protected string $foo; + + static protected final int $beep; + + static public final function bar() {} + + protected abstract function zim(); + + function zex() {} + } + + readonly final class ValueObject + { + // ... + } + + PHP, + new VersionSpecification(8_04_00), + ), + new CodeSample( + <<<'PHP' + ['const']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority(): int + { + return 56; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + /** + * @protected + * + * @TODO 4.0 move visibility from annotation to code when `VisibilityRequiredFixer` is removed + */ + public function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $elements = ['const', 'method', 'property']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'The structural elements to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($elements)]) + ->setDefault($elements) + ->getOption(), + ]); + } + + protected function configurePostNormalisation(): void + { + $this->elements = $this->configuration['elements']; + + if (\in_array('property', $this->elements, true)) { + $this->elements[] = 'promoted_property'; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) { + if (!\in_array($element['type'], $this->elements, true)) { + continue; + } + + $abstractFinalIndex = null; + $visibilityIndex = null; + $visibilitySetIndex = null; + $staticIndex = null; + $typeIndex = null; + $readOnlyIndex = null; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $expectedKinds = 'property' === $element['type'] || 'promoted_property' === $element['type'] + ? self::EXPECTED_KINDS_PROPERTY_KINDS + : self::EXPECTED_KINDS_GENERIC; + + while ($tokens[$prevIndex]->isGivenKind($expectedKinds) || $tokens[$prevIndex]->equals('&')) { + if ($tokens[$prevIndex]->isGivenKind([\T_ABSTRACT, \T_FINAL])) { + $abstractFinalIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind(\T_STATIC)) { + $staticIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind(FCT::T_READONLY)) { + $readOnlyIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind([FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET])) { + $visibilitySetIndex = $prevIndex; + } elseif ($tokens[$prevIndex]->isGivenKind(self::PROPERTY_TYPE_DECLARATION_KINDS)) { + $typeIndex = $prevIndex; + } elseif (!$tokens[$prevIndex]->equals('&')) { + $visibilityIndex = $prevIndex; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + if (null !== $typeIndex) { + $index = $typeIndex; + } + + if ('property' === $element['type'] && $tokens[$prevIndex]->equals(',')) { + continue; + } + + $swapIndex = $staticIndex ?? $readOnlyIndex; // "static" property cannot be "readonly", so there can always be at most one swap + + if (null !== $swapIndex) { + if ($this->isKeywordPlacedProperly($tokens, $swapIndex, $index)) { + $index = $swapIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $swapIndex, $index); + } + } + + if (null !== $visibilitySetIndex) { + if ($this->isKeywordPlacedProperly($tokens, $visibilitySetIndex, $index)) { + $index = $visibilitySetIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilitySetIndex, $index); + } + } + + if (null === $visibilityIndex) { + $tokens->insertAt($index, [new Token(['promoted_property' === $element['type'] ? CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC : \T_PUBLIC, 'public']), new Token([\T_WHITESPACE, ' '])]); + } else { + if ($tokens[$visibilityIndex]->isGivenKind(\T_VAR)) { + $tokens[$visibilityIndex] = new Token([\T_PUBLIC, 'public']); + } + if ($this->isKeywordPlacedProperly($tokens, $visibilityIndex, $index)) { + $index = $visibilityIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilityIndex, $index); + } + } + + if (null === $abstractFinalIndex) { + continue; + } + + if ($this->isKeywordPlacedProperly($tokens, $abstractFinalIndex, $index)) { + continue; + } + + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $abstractFinalIndex, $index); + } + } + + private function isKeywordPlacedProperly(Tokens $tokens, int $keywordIndex, int $comparedIndex): bool + { + return ' ' === $tokens[$keywordIndex + 1]->getContent() + && ( + $keywordIndex + 2 === $comparedIndex + || $keywordIndex + 3 === $comparedIndex && $tokens[$keywordIndex + 2]->equals('&') + ); + } + + private function moveTokenAndEnsureSingleSpaceFollows(Tokens $tokens, int $fromIndex, int $toIndex): void + { + $tokens->insertAt($toIndex, [$tokens[$fromIndex], new Token([\T_WHITESPACE, ' '])]); + $tokens->clearAt($fromIndex); + + if ($tokens[$fromIndex + 1]->isWhitespace()) { + $tokens->clearAt($fromIndex + 1); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php new file mode 100644 index 0000000..07d23d2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be no empty lines after class opening brace.', + [ + new CodeSample( + <<<'PHP' + $token) { + if (!$token->isClassy()) { + continue; + } + + $startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + if (!$tokens[$startBraceIndex + 1]->isWhitespace()) { + continue; + } + + $this->fixWhitespace($tokens, $startBraceIndex + 1); + } + } + + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + $tokens[$index] = new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding().substr($content, (int) strrpos($content, "\n") + 1)]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php new file mode 100644 index 0000000..9d8eb1e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoNullPropertyInitializationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Properties MUST not be explicitly initialised with `null` except when they have a type declaration (PHP 7.4).', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]) && $tokens->isAnyTokenKindsFound([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $inClass = []; + $classLevel = 0; + + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { // Enums and interfaces do not have properties + ++$classLevel; + $inClass[$classLevel] = 1; + + $index = $tokens->getNextTokenOfKind($index, ['{']); + + continue; + } + + if (0 === $classLevel) { + continue; + } + + \assert(isset($inClass[$classLevel])); + + if ($tokens[$index]->equals('{')) { + ++$inClass[$classLevel]; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$inClass[$classLevel]; + + if (0 === $inClass[$classLevel]) { + unset($inClass[$classLevel]); + --$classLevel; + } + + continue; + } + + // Ensure we are in a class but not in a method in case there are static variables defined + if (1 !== $inClass[$classLevel]) { + continue; + } + + if (!$tokens[$index]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC])) { + continue; + } + + while (true) { + $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_STATIC)) { + $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals('=')) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->equals([\T_STRING, 'null'], false)) { + for ($i = $varTokenIndex + 1; $i <= $index; ++$i) { + if ( + !($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n")) + && !$tokens[$i]->isComment() + ) { + $tokens->clearAt($i); + } + } + } + + ++$index; + } + + if (!$tokens[$index]->equals(',')) { + break; + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php new file mode 100644 index 0000000..d483933 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php @@ -0,0 +1,422 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @author Matteo Beccati + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoPhp4ConstructorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Convert PHP4-style constructors to `__construct`.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_CLASS); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $classes = array_keys($tokens->findGivenKind(\T_CLASS)); + $numClasses = \count($classes); + + for ($i = 0; $i < $numClasses; ++$i) { + \assert(isset($classes[$i])); + $index = $classes[$i]; + + // is it an anonymous class definition? + if ($tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + // is it inside a namespace? + $nspIndex = $tokens->getPrevTokenOfKind($index, [[\T_NAMESPACE, 'namespace']]); + + if (null !== $nspIndex) { + $nspIndex = $tokens->getNextMeaningfulToken($nspIndex); + + // make sure it's not the global namespace, as PHP4 constructors are allowed in there + if (!$tokens[$nspIndex]->equals('{')) { + // unless it's the global namespace, the index currently points to the name + $nspIndex = $tokens->getNextTokenOfKind($nspIndex, [';', '{']); + + if ($tokens[$nspIndex]->equals(';')) { + // the class is inside a (non-block) namespace, no PHP4-code should be in there + break; + } + + // the index points to the { of a block-namespace + $nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $nspIndex); + + if ($index < $nspEnd) { + // the class is inside a block namespace, skip other classes that might be in it + for ($j = $i + 1; $j < $numClasses; ++$j) { + \assert(isset($classes[$j])); + if ($classes[$j] < $nspEnd) { + ++$i; + } + } + + // and continue checking the classes that might follow + continue; + } + } + } + + $classNameIndex = $tokens->getNextMeaningfulToken($index); + $className = $tokens[$classNameIndex]->getContent(); + $classStart = $tokens->getNextTokenOfKind($classNameIndex, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classStart); + + $this->fixConstructor($tokens, $className, $classStart, $classEnd); + $this->fixParent($tokens, $classStart, $classEnd); + } + } + + /** + * Fix constructor within a class, if possible. + * + * @param Tokens $tokens the Tokens instance + * @param string $className the class name + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixConstructor(Tokens $tokens, string $className, int $classStart, int $classEnd): void + { + $php4 = $this->findFunction($tokens, $className, $classStart, $classEnd); + + if (null === $php4) { + return; // no PHP4-constructor! + } + + if (isset($php4['modifiers'][\T_ABSTRACT]) || isset($php4['modifiers'][\T_STATIC])) { + return; // PHP4 constructor can't be abstract or static + } + + $php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd); + + if (null === $php5) { + // no PHP5-constructor, we can rename the old one to __construct + $tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']); + + // in some (rare) cases we might have just created an infinite recursion issue + $this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']); + + return; + } + + // does the PHP4-constructor only call $this->__construct($args, ...)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']); + + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) { + // good, delete it! + for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) { + $tokens->clearAt($i); + } + + return; + } + } + + // does __construct only call the PHP4-constructor (with the same args)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']); + + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) { + // that was a weird choice, but we can safely delete it and... + for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) { + $tokens->clearAt($i); + } + + // rename the PHP4 one to __construct + $tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']); + + return; + } + } + } + + /** + * Fix calls to the parent constructor within a class. + * + * @param Tokens $tokens the Tokens instance + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixParent(Tokens $tokens, int $classStart, int $classEnd): void + { + // check calls to the parent constructor + foreach ($tokens->findGivenKind(\T_EXTENDS) as $index => $token) { + $parentIndex = $tokens->getNextMeaningfulToken($index); + $parentClass = $tokens[$parentIndex]->getContent(); + + // using parent::ParentClassName() or ParentClassName::ParentClassName() + $parentSeq = $tokens->findSequence([ + [\T_STRING], + [\T_DOUBLE_COLON], + [\T_STRING, $parentClass], + '(', + ], $classStart, $classEnd, [2 => false]); + + if (null !== $parentSeq) { + // we only need indices + $parentSeq = array_keys($parentSeq); + \assert(isset($parentSeq[2])); + + // match either of the possibilities + if ($tokens[$parentSeq[0]]->equalsAny([[\T_STRING, 'parent'], [\T_STRING, $parentClass]], false)) { + // replace with parent::__construct + $tokens[$parentSeq[0]] = new Token([\T_STRING, 'parent']); + $tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']); + } + } + + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // using $this->ParentClassName() + $parentSeq = $tokens->findSequence([ + [\T_VARIABLE, '$this'], + [$objectOperatorKind], + [\T_STRING, $parentClass], + '(', + ], $classStart, $classEnd, [2 => false]); + + if (null !== $parentSeq) { + // we only need indices + $parentSeq = array_keys($parentSeq); + \assert(isset($parentSeq[1], $parentSeq[2])); + + // replace call with parent::__construct() + $tokens[$parentSeq[0]] = new Token([ + \T_STRING, + 'parent', + ]); + $tokens[$parentSeq[1]] = new Token([ + \T_DOUBLE_COLON, + '::', + ]); + $tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']); + } + } + } + } + + /** + * Fix a particular infinite recursion issue happening when the parent class has __construct and the child has only + * a PHP4 constructor that calls the parent constructor as $this->__construct(). + * + * @param Tokens $tokens the Tokens instance + * @param int $start the PHP4 constructor body start + * @param int $end the PHP4 constructor body end + */ + private function fixInfiniteRecursion(Tokens $tokens, int $start, int $end): void + { + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + $seq = [ + [\T_VARIABLE, '$this'], + [$objectOperatorKind], + [\T_STRING, '__construct'], + ]; + + while (true) { + $callSeq = $tokens->findSequence($seq, $start, $end, [2 => false]); + + if (null === $callSeq) { + return; + } + + $callSeq = array_keys($callSeq); + \assert(isset($callSeq[1])); + + $tokens[$callSeq[0]] = new Token([\T_STRING, 'parent']); + $tokens[$callSeq[1]] = new Token([\T_DOUBLE_COLON, '::']); + } + } + } + + /** + * Generate the sequence of tokens necessary for the body of a wrapper method that simply + * calls $this->{$method}( [args...] ) with the same arguments as its own signature. + * + * @param Tokens $tokens the Tokens instance + * @param string $method the wrapped method name + * @param int $startIndex function/method start index + * @param int $bodyIndex function/method body index + * + * @return array{non-empty-list>, array{3: false}} + */ + private function getWrapperMethodSequence(Tokens $tokens, string $method, int $startIndex, int $bodyIndex): array + { + $sequences = []; + + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // initialise sequence as { $this->{$method}( + $seq = [ + '{', + [\T_VARIABLE, '$this'], + [$objectOperatorKind], + [\T_STRING, $method], + '(', + ]; + + // parse method parameters, if any + $index = $startIndex; + + while (true) { + // find the next variable name + $index = $tokens->getNextTokenOfKind($index, [[\T_VARIABLE]]); + + if (null === $index || $index >= $bodyIndex) { + // we've reached the body already + break; + } + + // append a comma if it's not the first variable + if (\count($seq) > 5) { + $seq[] = ','; + } + + // append variable name to the sequence + $seq[] = [\T_VARIABLE, $tokens[$index]->getContent()]; + } + + // almost done, close the sequence with ); } + $seq[] = ')'; + $seq[] = ';'; + $seq[] = '}'; + + $sequences[] = $seq; + } + + return [$sequences, [3 => false]]; + } + + /** + * Find a function or method matching a given name within certain bounds. + * + * Returns: + * - nameIndex (int): The index of the function/method name. + * - startIndex (int): The index of the function/method start. + * - endIndex (int): The index of the function/method end. + * - bodyIndex (int): The index of the function/method body. + * - modifiers (array): The modifiers as array keys and their index as the values, e.g. array(T_PUBLIC => 10) + * + * @param Tokens $tokens the Tokens instance + * @param string $name the function/Method name + * @param int $startIndex the search start index + * @param int $endIndex the search end index + * + * @return null|array{ + * nameIndex: int, + * startIndex: int, + * endIndex: int, + * bodyIndex: int, + * modifiers: list, + * } + */ + private function findFunction(Tokens $tokens, string $name, int $startIndex, int $endIndex): ?array + { + $function = $tokens->findSequence([ + [\T_FUNCTION], + [\T_STRING, $name], + '(', + ], $startIndex, $endIndex, false); + + if (null === $function) { + return null; + } + + // keep only the indices + $function = array_keys($function); + \assert(isset($function[1], $function[2])); + + // find previous block, saving method modifiers for later use + $possibleModifiers = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_STATIC, \T_ABSTRACT, \T_FINAL]; + $modifiers = []; + + $prevBlock = $tokens->getPrevMeaningfulToken($function[0]); + + while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) { + $modifiers[$tokens[$prevBlock]->getId()] = $prevBlock; + $prevBlock = $tokens->getPrevMeaningfulToken($prevBlock); + } + + if (isset($modifiers[\T_ABSTRACT])) { + // abstract methods have no body + $bodyStart = null; + $funcEnd = $tokens->getNextTokenOfKind($function[2], [';']); + } else { + // find method body start and the end of the function definition + $bodyStart = $tokens->getNextTokenOfKind($function[2], ['{']); + $funcEnd = null !== $bodyStart ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $bodyStart) : null; + } + + return [ + 'nameIndex' => $function[1], + 'startIndex' => $prevBlock + 1, + 'endIndex' => $funcEnd, + 'bodyIndex' => $bodyStart, + 'modifiers' => $modifiers, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoRedundantReadonlyPropertyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoRedundantReadonlyPropertyFixer.php new file mode 100644 index 0000000..e57e280 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoRedundantReadonlyPropertyFixer.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Removes redundant readonly from properties in readonly classes. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoRedundantReadonlyPropertyFixer extends AbstractFixer +{ + private const PROPERTY_TYPE_DECLARATION_KINDS = [\T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + private const EXPECTED_KINDS_GENERIC = [\T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + private const EXPECTED_KINDS_PROPERTY_KINDS = [...self::EXPECTED_KINDS_GENERIC, ...self::PROPERTY_TYPE_DECLARATION_KINDS]; + + /** + * {@inheritdoc} + * + * Must run after PhpdocReadonlyClassCommentToKeywordFixer. + */ + public function getPriority(): int + { + return 3; + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_02_00 && $tokens->isAnyTokenKindsFound([\T_CLASS]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes redundant readonly from properties in readonly classes.', + [ + new VersionSpecificCodeSample( + <<<'PHP' + getClassyElements() as $index => $element) { + if (!\in_array($element['type'], ['property', 'promoted_property'], true)) { + continue; + } + + $modifiers = $tokensAnalyzer->getClassyModifiers($element['classIndex']); + if (null === $modifiers['readonly']) { + continue; + } + + $readOnlyIndex = null; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + while ($tokens[$prevIndex]->isGivenKind(self::EXPECTED_KINDS_PROPERTY_KINDS) || $tokens[$prevIndex]->equals('&')) { + if ($tokens[$prevIndex]->isGivenKind(FCT::T_READONLY)) { + $readOnlyIndex = $prevIndex; + + break; + } + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + if (null !== $readOnlyIndex) { + $tokens->removeTrailingWhitespace($readOnlyIndex); + $tokens->clearAt($readOnlyIndex); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php new file mode 100644 index 0000000..2f54da1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php @@ -0,0 +1,218 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * private_methods?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * private_methods: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnneededFinalMethodFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes `final` from methods where possible.', + [ + new CodeSample( + <<<'PHP' + false], + ), + ], + null, + 'Risky when child class overrides a `private` method.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + if (!$tokens->isAllTokenKindsFound([\T_FINAL, \T_FUNCTION])) { + return false; + } + + return $tokens->isAnyTokenKindsFound([\T_CLASS, FCT::T_ENUM]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->getMethods($tokens) as $element) { + $index = $element['method_final_index']; + + if ($element['method_of_enum'] || $element['class_is_final']) { + $this->clearFinal($tokens, $index); + + continue; + } + + if (!$element['method_is_private'] || false === $this->configuration['private_methods'] || $element['method_is_constructor']) { + continue; + } + + $this->clearFinal($tokens, $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('private_methods', 'Private methods of non-`final` classes must not be declared `final`.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @return iterable + */ + private function getMethods(Tokens $tokens): iterable + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifierKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_STATIC]; + + $enums = []; + $classesAreFinal = []; + + foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { + if ('method' !== $element['type']) { + continue; // not a method + } + + $classIndex = $element['classIndex']; + + if (!\array_key_exists($classIndex, $enums)) { + $enums[$classIndex] = $tokens[$classIndex]->isGivenKind(FCT::T_ENUM); + } + + $element['method_final_index'] = null; + $element['method_is_private'] = false; + + $previous = $index; + + do { + $previous = $tokens->getPrevMeaningfulToken($previous); + + if ($tokens[$previous]->isGivenKind(\T_PRIVATE)) { + $element['method_is_private'] = true; + } elseif ($tokens[$previous]->isGivenKind(\T_FINAL)) { + $element['method_final_index'] = $previous; + } + } while ($tokens[$previous]->isGivenKind($modifierKinds)); + + if ($enums[$classIndex]) { + $element['method_of_enum'] = true; + + yield $element; + + continue; + } + + if (!\array_key_exists($classIndex, $classesAreFinal)) { + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + $classesAreFinal[$classIndex] = isset($modifiers['final']); + } + + $element['method_of_enum'] = false; + $element['class_is_final'] = $classesAreFinal[$classIndex]; + $element['method_is_constructor'] = '__construct' === strtolower($tokens[$tokens->getNextMeaningfulToken($index)]->getContent()); + + yield $element; + } + } + + private function clearFinal(Tokens $tokens, ?int $index): void + { + if (null === $index) { + return; + } + + $tokens->clearAt($index); + + ++$index; + + if ($tokens[$index]->isWhitespace()) { + $tokens->clearAt($index); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php new file mode 100644 index 0000000..f9ade24 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php @@ -0,0 +1,635 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @phpstan-type _ClassElement array{ + * start: int, + * visibility: string, + * abstract: bool, + * static: bool, + * readonly: bool, + * type: string, + * name: string, + * end: int, + * } + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * order?: list, + * sort_algorithm?: 'alpha'|'none', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * order: list, + * sort_algorithm: 'alpha'|'none', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedClassElementsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @internal */ + public const SORT_ALPHA = 'alpha'; + + /** @internal */ + public const SORT_NONE = 'none'; + + private const SUPPORTED_SORT_ALGORITHMS = [ + self::SORT_NONE, + self::SORT_ALPHA, + ]; + + /** + * @var array> Array containing all class element base types (keys) and their parent types (values) + */ + private const TYPE_HIERARCHY = [ + 'use_trait' => null, + 'public' => null, + 'protected' => null, + 'private' => null, + 'case' => ['public'], + 'constant' => null, + 'constant_public' => ['constant', 'public'], + 'constant_protected' => ['constant', 'protected'], + 'constant_private' => ['constant', 'private'], + 'property' => null, + 'property_static' => ['property'], + 'property_public' => ['property', 'public'], + 'property_protected' => ['property', 'protected'], + 'property_private' => ['property', 'private'], + 'property_public_abstract' => ['property_abstract', 'property_public'], + 'property_public_readonly' => ['property_readonly', 'property_public'], + 'property_protected_abstract' => ['property_abstract', 'property_protected'], + 'property_protected_readonly' => ['property_readonly', 'property_protected'], + 'property_private_readonly' => ['property_readonly', 'property_private'], + 'property_public_static' => ['property_static', 'property_public'], + 'property_protected_static' => ['property_static', 'property_protected'], + 'property_private_static' => ['property_static', 'property_private'], + 'method' => null, + 'method_abstract' => ['method'], + 'method_static' => ['method'], + 'method_public' => ['method', 'public'], + 'method_protected' => ['method', 'protected'], + 'method_private' => ['method', 'private'], + 'method_public_abstract' => ['method_abstract', 'method_public'], + 'method_protected_abstract' => ['method_abstract', 'method_protected'], + 'method_private_abstract' => ['method_abstract', 'method_private'], + 'method_public_abstract_static' => ['method_abstract', 'method_static', 'method_public'], + 'method_protected_abstract_static' => ['method_abstract', 'method_static', 'method_protected'], + 'method_private_abstract_static' => ['method_abstract', 'method_static', 'method_private'], + 'method_public_static' => ['method_static', 'method_public'], + 'method_protected_static' => ['method_static', 'method_protected'], + 'method_private_static' => ['method_static', 'method_private'], + ]; + + /** + * @var array Array containing special method types + */ + private const SPECIAL_TYPES = [ + 'construct' => null, + 'destruct' => null, + 'magic' => null, + 'phpunit' => null, + ]; + + /** + * @var array Resolved configuration array (type => position) + */ + private array $typePosition; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders the elements of classes/interfaces/traits/enums.', + [ + new CodeSample( + <<<'PHP' + ['method_private', 'method_public']], + ), + new CodeSample( + <<<'PHP' + ['method_public'], 'sort_algorithm' => self::SORT_ALPHA], + ), + new CodeSample( + <<<'PHP' + ['method_public'], 'sort_algorithm' => self::SORT_ALPHA, 'case_sensitive' => true], + ), + ], + 'Accepts a subset of pre-defined element types, special element groups, and custom patterns. + +Element types: `[\''.implode('\', \'', array_keys(self::TYPE_HIERARCHY)).'\']` + +Special element types: `[\''.implode('\', \'', array_keys(self::SPECIAL_TYPES)).'\']` + +Custom values: + +- `method:*`: specify a single method name (e.g. `method:__invoke`) to set the order of that specific method.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer, PhpUnitDataProviderMethodOrderFixer, SpaceAfterSemicolonFixer. + * Must run after NoPhp4ConstructorFixer, ProtectedToPrivateFixer. + */ + public function getPriority(): int + { + return 65; + } + + protected function configurePostNormalisation(): void + { + $this->typePosition = []; + $position = 0; + + foreach ($this->configuration['order'] as $type) { + $this->typePosition[$type] = $position++; + } + + foreach (self::TYPE_HIERARCHY as $type => $parents) { + if (isset($this->typePosition[$type])) { + continue; + } + + if (null === $parents) { + $this->typePosition[$type] = null; + + continue; + } + + foreach ($parents as $parent) { + if (isset($this->typePosition[$parent])) { + $this->typePosition[$type] = $this->typePosition[$parent]; + + continue 2; + } + } + + $this->typePosition[$type] = null; + } + + $lastPosition = \count($this->configuration['order']); + + foreach ($this->typePosition as &$pos) { + if (null === $pos) { + $pos = $lastPosition; + } + + $pos *= 10; // last digit is used by phpunit method ordering + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($i = 1, $count = $tokens->count(); $i < $count; ++$i) { + if (!$tokens[$i]->isClassy()) { + continue; + } + + $i = $tokens->getNextTokenOfKind($i, ['{']); + $elements = $this->getElements($tokens, $i); + + if (0 === \count($elements)) { + continue; + } + + $endIndex = $elements[array_key_last($elements)]['end']; + + $sorted = $this->sortElements($elements); + + if ($sorted !== $elements) { + $this->sortTokens($tokens, $i, $endIndex, $sorted); + } + + $i = $endIndex; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $builtIns = array_keys(array_merge(self::TYPE_HIERARCHY, self::SPECIAL_TYPES)); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('order', 'List of strings defining order of elements.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([ + static function (array $values) use ($builtIns): bool { + foreach ($values as $value) { + if (\in_array($value, $builtIns, true)) { + return true; + } + + if ('method:' === substr($value, 0, 7)) { + return true; + } + } + + return false; + }, + ]) + ->setDefault([ + 'use_trait', + 'case', + 'constant_public', + 'constant_protected', + 'constant_private', + 'property_public', + 'property_protected', + 'property_private', + 'construct', + 'destruct', + 'magic', + 'phpunit', + 'method_public', + 'method_protected', + 'method_private', + ]) + ->getOption(), + (new FixerOptionBuilder('sort_algorithm', 'How multiple occurrences of same type statements should be sorted.')) + ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) + ->setDefault(self::SORT_NONE) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return list<_ClassElement> + */ + private function getElements(Tokens $tokens, int $startIndex): array + { + ++$startIndex; + $elements = []; + + while (true) { + $element = [ + 'start' => $startIndex, + 'visibility' => 'public', + 'abstract' => false, + 'static' => false, + 'readonly' => false, + ]; + + for ($i = $startIndex;; ++$i) { + $token = $tokens[$i]; + + if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $i); + + continue; + } + + // class end + if ($token->equals('}')) { + return $elements; + } + + if ($token->isGivenKind(\T_ABSTRACT)) { + $element['abstract'] = true; + + continue; + } + + if ($token->isGivenKind(\T_STATIC)) { + $element['static'] = true; + + continue; + } + + if ($token->isGivenKind(FCT::T_READONLY)) { + $element['readonly'] = true; + } + + if ($token->isGivenKind([\T_PROTECTED, \T_PRIVATE])) { + $element['visibility'] = strtolower($token->getContent()); + + continue; + } + + if (!$token->isGivenKind([CT::T_USE_TRAIT, \T_CASE, \T_CONST, \T_VARIABLE, \T_FUNCTION])) { + continue; + } + + $type = $this->detectElementType($tokens, $i); + + if (\is_array($type)) { + $element['type'] = $type[0]; + $element['name'] = $type[1]; + } else { + $element['type'] = $type; + } + + if ('property' === $element['type']) { + $element['name'] = $tokens[$i]->getContent(); + } elseif ('constant' === $element['type']) { + $equalsSignIndex = $tokens->getNextTokenOfKind($i, ['=']); + $element['name'] = $tokens[$tokens->getPrevMeaningfulToken($equalsSignIndex)]->getContent(); + } elseif (\in_array($element['type'], ['use_trait', 'case', 'method', 'magic', 'construct', 'destruct'], true)) { + $element['name'] = $tokens[$tokens->getNextMeaningfulToken($i)]->getContent(); + } + + $element['end'] = $this->findElementEnd($tokens, $i); + + break; + } + + $elements[] = $element; + $startIndex = $element['end'] + 1; + } + } + + /** + * @return list{string, string}|string type or array of type and name + */ + private function detectElementType(Tokens $tokens, int $index) + { + $token = $tokens[$index]; + + if ($token->isGivenKind(CT::T_USE_TRAIT)) { + return 'use_trait'; + } + + if ($token->isGivenKind(\T_CASE)) { + return 'case'; + } + + if ($token->isGivenKind(\T_CONST)) { + return 'constant'; + } + + if ($token->isGivenKind(\T_VARIABLE)) { + return 'property'; + } + + $nameToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + if ($nameToken->equals([\T_STRING, '__construct'], false)) { + return 'construct'; + } + + if ($nameToken->equals([\T_STRING, '__destruct'], false)) { + return 'destruct'; + } + + if ( + $nameToken->equalsAny([ + [\T_STRING, 'setUpBeforeClass'], + [\T_STRING, 'doSetUpBeforeClass'], + [\T_STRING, 'tearDownAfterClass'], + [\T_STRING, 'doTearDownAfterClass'], + [\T_STRING, 'setUp'], + [\T_STRING, 'doSetUp'], + [\T_STRING, 'assertPreConditions'], + [\T_STRING, 'assertPostConditions'], + [\T_STRING, 'tearDown'], + [\T_STRING, 'doTearDown'], + ], false) + ) { + return ['phpunit', strtolower($nameToken->getContent())]; + } + + return str_starts_with($nameToken->getContent(), '__') ? 'magic' : 'method'; + } + + private function findElementEnd(Tokens $tokens, int $index): int + { + $index = $tokens->getNextTokenOfKind($index, ['(', '{', ';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]]); + + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getNextTokenOfKind($index, ['{', ';']); + } + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + } + + if ($tokens[$index]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $index); + } + + for (++$index; $tokens[$index]->isWhitespace(" \t") || $tokens[$index]->isComment(); ++$index); + + --$index; + + return $tokens[$index]->isWhitespace() ? $index - 1 : $index; + } + + /** + * @param list<_ClassElement> $elements + * + * @return list<_ClassElement> + */ + private function sortElements(array $elements): array + { + return Utils::stableSort( + $elements, + /** + * @return array{element: _ClassElement, position: int} + */ + fn (array $element): array => ['element' => $element, 'position' => $this->getTypePosition($element)], + /** + * @param array{element: _ClassElement, position: int} $a + * @param array{element: _ClassElement, position: int} $b + * + * @return -1|0|1 + */ + fn (array $a, array $b): int => ($a['position'] === $b['position']) ? $this->sortGroupElements($a['element'], $b['element']) : $a['position'] <=> $b['position'], + ); + } + + /** + * @param _ClassElement $element + */ + private function getTypePosition(array $element): int + { + $type = $element['type']; + + if (\in_array($type, ['method', 'magic', 'phpunit'], true) && isset($this->typePosition["method:{$element['name']}"])) { + return $this->typePosition["method:{$element['name']}"]; + } + + if (\array_key_exists($type, self::SPECIAL_TYPES)) { + if (isset($this->typePosition[$type])) { + $position = $this->typePosition[$type]; + + if ('phpunit' === $type) { + \assert(\in_array($element['name'], ['setupbeforeclass', 'dosetupbeforeclass', 'teardownafterclass', 'doteardownafterclass', 'setup', 'dosetup', 'assertpreconditions', 'assertpostconditions', 'teardown', 'doteardown'], true)); + $position += [ + 'setupbeforeclass' => 1, + 'dosetupbeforeclass' => 2, + 'teardownafterclass' => 3, + 'doteardownafterclass' => 4, + 'setup' => 5, + 'dosetup' => 6, + 'assertpreconditions' => 7, + 'assertpostconditions' => 8, + 'teardown' => 9, + 'doteardown' => 10, + ][$element['name']]; + } + + return $position; + } + + $type = 'method'; + } + + if (\in_array($type, ['constant', 'property', 'method'], true)) { + $type .= '_'.$element['visibility']; + + if ($element['abstract']) { + $type .= '_abstract'; + } + + if ($element['static']) { + $type .= '_static'; + } + + if ($element['readonly']) { + $type .= '_readonly'; + } + } + + \assert(isset($this->typePosition[$type])); + + return $this->typePosition[$type]; + } + + /** + * @param _ClassElement $a + * @param _ClassElement $b + */ + private function sortGroupElements(array $a, array $b): int + { + if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { + return true === $this->configuration['case_sensitive'] + ? $a['name'] <=> $b['name'] + : strcasecmp($a['name'], $b['name']); + } + + return $a['start'] <=> $b['start']; + } + + /** + * @param list<_ClassElement> $elements + */ + private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements): void + { + $replaceTokens = []; + + foreach ($elements as $element) { + for ($i = $element['start']; $i <= $element['end']; ++$i) { + $replaceTokens[] = clone $tokens[$i]; + } + } + + $tokens->overrideRange($startIndex + 1, $endIndex, $replaceTokens); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php new file mode 100644 index 0000000..00712cb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php @@ -0,0 +1,275 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * direction?: 'ascend'|'descend', + * order?: 'alpha'|'length', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * direction: 'ascend'|'descend', + * order: 'alpha'|'length', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dave van der Brugge + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedInterfacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @internal */ + public const OPTION_DIRECTION = 'direction'; + + /** @internal */ + public const OPTION_ORDER = 'order'; + + /** @internal */ + public const DIRECTION_ASCEND = 'ascend'; + + /** @internal */ + public const DIRECTION_DESCEND = 'descend'; + + /** @internal */ + public const ORDER_ALPHA = 'alpha'; + + /** @internal */ + public const ORDER_LENGTH = 'length'; + + /** + * Array of supported directions in configuration. + * + * @var non-empty-list + */ + private const SUPPORTED_DIRECTION_OPTIONS = [ + self::DIRECTION_ASCEND, + self::DIRECTION_DESCEND, + ]; + + /** + * Array of supported orders in configuration. + * + * @var non-empty-list + */ + private const SUPPORTED_ORDER_OPTIONS = [ + self::ORDER_ALPHA, + self::ORDER_LENGTH, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders the interfaces in an `implements` or `interface extends` clause.', + [ + new CodeSample( + " self::DIRECTION_DESCEND], + ), + new CodeSample( + " self::ORDER_LENGTH], + ), + new CodeSample( + " self::ORDER_LENGTH, + self::OPTION_DIRECTION => self::DIRECTION_DESCEND, + ], + ), + new CodeSample( + " self::ORDER_ALPHA, + ], + ), + new CodeSample( + " self::ORDER_ALPHA, + 'case_sensitive' => true, + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after FullyQualifiedStrictTypesFixer, StringableForToStringFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_IMPLEMENTS) + || $tokens->isAllTokenKindsFound([\T_INTERFACE, \T_EXTENDS]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_IMPLEMENTS)) { + if (!$token->isGivenKind(\T_EXTENDS)) { + continue; + } + + $nameTokenIndex = $tokens->getPrevMeaningfulToken($index); + $interfaceTokenIndex = $tokens->getPrevMeaningfulToken($nameTokenIndex); + $interfaceToken = $tokens[$interfaceTokenIndex]; + + if (!$interfaceToken->isGivenKind(\T_INTERFACE)) { + continue; + } + } + + $implementsStart = $index + 1; + $implementsEnd = $tokens->getPrevMeaningfulToken($tokens->getNextTokenOfKind($implementsStart, ['{'])); + + $interfacesTokens = $this->getInterfaces($tokens, $implementsStart, $implementsEnd); + + if (1 === \count($interfacesTokens)) { + continue; + } + + $interfaces = []; + foreach ($interfacesTokens as $interfaceIndex => $interface) { + $interfaceTokens = Tokens::fromArray($interface); + $normalized = ''; + $actualInterfaceIndex = $interfaceTokens->getNextMeaningfulToken(-1); + + while ($interfaceTokens->offsetExists($actualInterfaceIndex)) { + $token = $interfaceTokens[$actualInterfaceIndex]; + + if ($token->isComment() || $token->isWhitespace()) { + break; + } + + $normalized .= str_replace('\\', ' ', $token->getContent()); + ++$actualInterfaceIndex; + } + + $interfaces[$interfaceIndex] = [ + 'tokens' => $interface, + 'normalized' => $normalized, + 'originalIndex' => $interfaceIndex, + ]; + } + + usort($interfaces, function (array $first, array $second): int { + $score = self::ORDER_LENGTH === $this->configuration[self::OPTION_ORDER] + ? \strlen($first['normalized']) - \strlen($second['normalized']) + : ( + true === $this->configuration['case_sensitive'] + ? $first['normalized'] <=> $second['normalized'] + : strcasecmp($first['normalized'], $second['normalized']) + ); + + if (self::DIRECTION_DESCEND === $this->configuration[self::OPTION_DIRECTION]) { + $score *= -1; + } + + return $score; + }); + + $changed = false; + + foreach ($interfaces as $interfaceIndex => $interface) { + if ($interface['originalIndex'] !== $interfaceIndex) { + $changed = true; + + break; + } + } + + if (!$changed) { + continue; + } + + $newTokens = array_shift($interfaces)['tokens']; + + foreach ($interfaces as $interface) { + array_push($newTokens, new Token(','), ...$interface['tokens']); + } + + $tokens->overrideRange($implementsStart, $implementsEnd, $newTokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_ORDER, 'How the interfaces should be ordered.')) + ->setAllowedValues(self::SUPPORTED_ORDER_OPTIONS) + ->setDefault(self::ORDER_ALPHA) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_DIRECTION, 'Which direction the interfaces should be ordered.')) + ->setAllowedValues(self::SUPPORTED_DIRECTION_OPTIONS) + ->setDefault(self::DIRECTION_ASCEND) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return array> + */ + private function getInterfaces(Tokens $tokens, int $implementsStart, int $implementsEnd): array + { + $interfaces = []; + $interfaceIndex = 0; + + for ($i = $implementsStart; $i <= $implementsEnd; ++$i) { + if ($tokens[$i]->equals(',')) { + ++$interfaceIndex; + $interfaces[$interfaceIndex] = []; + + continue; + } + + $interfaces[$interfaceIndex][] = $tokens[$i]; + } + + return $interfaces; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php new file mode 100644 index 0000000..aa66097 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php @@ -0,0 +1,231 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedTraitsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Trait `use` statements must be sorted alphabetically.', + [ + new CodeSample(" true, + ], + ), + ], + null, + 'Risky when depending on order of the imports.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(CT::T_USE_TRAIT); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->findUseStatementsGroups($tokens) as $uses) { + $this->sortUseStatements($tokens, $uses); + } + } + + /** + * @return iterable> + */ + private function findUseStatementsGroups(Tokens $tokens): iterable + { + $uses = []; + + for ($index = 1, $max = \count($tokens); $index < $max; ++$index) { + $token = $tokens[$index]; + + if ($token->isWhitespace() || $token->isComment()) { + continue; + } + + if (!$token->isGivenKind(CT::T_USE_TRAIT)) { + if (\count($uses) > 0) { + yield $uses; + + $uses = []; + } + + continue; + } + + $startIndex = $tokens->getNextNonWhitespace($tokens->getPrevMeaningfulToken($index)); + \assert(\is_int($startIndex)); + + $endIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + + if ($tokens[$endIndex]->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $endIndex); + } + + $use = []; + + for ($i = $startIndex; $i <= $endIndex; ++$i) { + $use[] = $tokens[$i]; + } + + $uses[$startIndex] = Tokens::fromArray($use); + + $index = $endIndex; + } + } + + /** + * @param array $uses + */ + private function sortUseStatements(Tokens $tokens, array $uses): void + { + foreach ($uses as $use) { + $this->sortMultipleTraitsInStatement($use); + } + + $this->sort($tokens, $uses); + } + + private function sortMultipleTraitsInStatement(Tokens $use): void + { + $traits = []; + $indexOfName = null; + $name = []; + + for ($index = 0, $max = \count($use); $index < $max; ++$index) { + $token = $use[$index]; + + if ($token->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + $name[] = $token; + + if (null === $indexOfName) { + $indexOfName = $index; + } + + continue; + } + + if ($token->equalsAny([',', ';', '{'])) { + \assert(null !== $indexOfName); + $traits[$indexOfName] = Tokens::fromArray($name); + + $name = []; + $indexOfName = null; + } + + if ($token->equals('{')) { + $index = $use->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + } + } + + $this->sort($use, $traits); + } + + /** + * @param array $elements + */ + private function sort(Tokens $tokens, array $elements): void + { + $toTraitName = static function (Tokens $use): string { + $string = ''; + + foreach ($use as $token) { + if ($token->equalsAny([';', '{'])) { + break; + } + + if ($token->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) { + $string .= $token->getContent(); + } + } + + return ltrim($string, '\\'); + }; + + $sortedElements = $elements; + uasort( + $sortedElements, + fn (Tokens $useA, Tokens $useB): int => true === $this->configuration['case_sensitive'] + ? $toTraitName($useA) <=> $toTraitName($useB) + : strcasecmp($toTraitName($useA), $toTraitName($useB)), + ); + + $sortedElements = array_combine( + array_keys($elements), + array_values($sortedElements), + ); + + $beforeOverrideCount = $tokens->count(); + + foreach (array_reverse($sortedElements, true) as $index => $tokensToInsert) { + $tokens->overrideRange( + $index, + $index + \count($elements[$index]) - 1, + $tokensToInsert, + ); + } + + if ($beforeOverrideCount < $tokens->count()) { + $tokens->clearEmptyTokens(); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php new file mode 100644 index 0000000..1b85987 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php @@ -0,0 +1,464 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * null_adjustment?: 'always_first'|'always_last'|'none', + * sort_algorithm?: 'alpha'|'none', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * null_adjustment: 'always_first'|'always_last'|'none', + * sort_algorithm: 'alpha'|'none', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author John Paul E. Balandan, CPA + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedTypesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Sort union types and intersection types using configured order.', + [ + new CodeSample( + <<<'PHP' + save($foo); + } catch (\RuntimeException|CacheException $e) { + logger($e); + + throw $e; + } + + PHP, + ), + new VersionSpecificCodeSample( + <<<'PHP' + true, + ], + ), + new VersionSpecificCodeSample( + <<<'PHP' + 'always_last'], + ), + new VersionSpecificCodeSample( + <<<'PHP' + 'none', + 'null_adjustment' => 'always_last', + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before TypesSpacesFixer. + * Must run after NullableTypeDeclarationFixer, NullableTypeDeclarationForDefaultNullValueFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'Whether the types should be sorted alphabetically, or not sorted.')) + ->setAllowedValues(['alpha', 'none']) + ->setDefault('alpha') + ->getOption(), + (new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).')) + ->setAllowedValues(['always_first', 'always_last', 'none']) + ->setDefault( + Future::getV4OrV3( + 'always_last', // as recommended in https://github.com/php-fig/per-coding-style/blob/master/migration-3.0.md#section-25---keywords-and-types + 'always_first', + ), + ) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach ($this->getElements($tokens) as $index => $type) { + if ('catch' === $type) { + $this->fixCatchArgumentType($tokens, $index); + + continue; + } + + if ('property' === $type) { + $this->fixPropertyType($tokens, $index); + + continue; + } + + $this->fixMethodArgumentType($functionsAnalyzer, $tokens, $index); + $this->fixMethodReturnType($functionsAnalyzer, $tokens, $index); + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true), + ), + ); + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_CATCH)) { + $elements[$index] = 'catch'; + + continue; + } + + if ( + $token->isGivenKind(\T_FN) + || ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'method'; + } + } + + return $elements; + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + + private function fixCatchArgumentType(Tokens $tokens, int $index): void + { + $catchStart = $tokens->getNextTokenOfKind($index, ['(']); + $catchEnd = $tokens->getNextTokenOfKind($catchStart, [')', [\T_VARIABLE]]); + + $catchArgumentType = $this->collectTypeAnalysis($tokens, $catchStart, $catchEnd); + + if (null === $catchArgumentType || !$this->isTypeSortable($catchArgumentType)) { + return; // nothing to fix + } + + $this->sortTypes($catchArgumentType, $tokens); + } + + private function fixPropertyType(Tokens $tokens, int $index): void + { + $propertyIndex = $index; + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + + if (null === $propertyType || !$this->isTypeSortable($propertyType)) { + return; // nothing to fix + } + + $this->sortTypes($propertyType, $tokens); + } + + private function fixMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach ($functionsAnalyzer->getFunctionArguments($tokens, $index) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType || !$this->isTypeSortable($argumentType)) { + continue; // nothing to fix + } + + $this->sortTypes($argumentType, $tokens); + } + } + + private function fixMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null === $returnType || !$this->isTypeSortable($returnType)) { + return; // nothing to fix + } + + $this->sortTypes($returnType, $tokens); + } + + private function sortTypes(TypeAnalysis $typeAnalysis, Tokens $tokens): void + { + $type = $typeAnalysis->getName(); + + if (str_contains($type, '|') && str_contains($type, '&')) { + // a DNF type of the form (A&B)|C, available as of PHP 8.2 + [$originalTypes, $glue] = $this->collectDisjunctiveNormalFormTypes($type); + } else { + [$originalTypes, $glue] = $this->collectUnionOrIntersectionTypes($type); + } + + // If the $types array is coming from a DNF type, then we have parts + // which are also array. If so, we sort those sub-types first before + // running the sorting algorithm to the entire $types array. + $sortedTypes = array_map(function ($subType) { + if (\is_array($subType)) { + return $this->runTypesThroughSortingAlgorithm($subType); + } + + return $subType; + }, $originalTypes); + + $sortedTypes = $this->runTypesThroughSortingAlgorithm($sortedTypes); + + if ($sortedTypes === $originalTypes) { + return; + } + + $tokens->overrideRange( + $typeAnalysis->getStartIndex(), + $typeAnalysis->getEndIndex(), + $this->createTypeDeclarationTokens($sortedTypes, $glue), + ); + } + + private function isTypeSortable(TypeAnalysis $type): bool + { + return str_contains($type->getName(), '|') || str_contains($type->getName(), '&'); + } + + /** + * @return array{0: non-empty-list|string>, 1: string} + */ + private function collectDisjunctiveNormalFormTypes(string $type): array + { + $types = array_map(static function (string $subType) { + if (str_starts_with($subType, '(')) { + return explode('&', trim($subType, '()')); + } + + return $subType; + }, explode('|', $type)); + + return [$types, '|']; + } + + /** + * @return array{0: non-empty-list, 1: string} + */ + private function collectUnionOrIntersectionTypes(string $type): array + { + $types = explode('|', $type); + $glue = '|'; + + if (1 === \count($types)) { + $types = explode('&', $type); + $glue = '&'; + } + + return [$types, $glue]; + } + + /** + * @param list|string> $types + * + * @return ($types is list ? list : list>) + */ + private function runTypesThroughSortingAlgorithm(array $types): array + { + $normalizeType = static fn (string $type): string => Preg::replace('/^\\\?/', '', $type); + + usort($types, function ($a, $b) use ($normalizeType): int { + if (\is_array($a)) { + $a = implode('&', $a); + } + + if (\is_array($b)) { + $b = implode('&', $b); + } + + $a = $normalizeType($a); + $b = $normalizeType($b); + $lowerCaseA = strtolower($a); + $lowerCaseB = strtolower($b); + + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + + if ('alpha' === $this->configuration['sort_algorithm']) { + return true === $this->configuration['case_sensitive'] ? $a <=> $b : strcasecmp($a, $b); + } + + return 0; + }); + + return $types; + } + + /** + * @param list|string> $types + * + * @return list + */ + private function createTypeDeclarationTokens(array $types, string $glue, bool $isDisjunctive = false): array + { + $specialTypes = [ + 'array' => [CT::T_ARRAY_TYPEHINT, 'array'], + 'callable' => [\T_CALLABLE, 'callable'], + 'static' => [\T_STATIC, 'static'], + ]; + + $count = \count($types); + $newTokens = []; + + foreach ($types as $i => $type) { + if (\is_array($type)) { + $newTokens = [ + ...$newTokens, + ...$this->createTypeDeclarationTokens($type, '&', true), + ]; + } elseif (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + foreach (explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + + if ($nsIndex > 0) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([\T_STRING, $value]); + } + } + + if ($i <= $count - 2) { + $newTokens[] = new Token([ + '|' => [CT::T_TYPE_ALTERNATION, '|'], + '&' => [CT::T_TYPE_INTERSECTION, '&'], + ][$glue]); + } + } + + if ($isDisjunctive) { + array_unshift($newTokens, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $newTokens[] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + + return $newTokens; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php new file mode 100644 index 0000000..f0d8541 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Marcel Behrmann + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocReadonlyClassCommentToKeywordFixer extends AbstractFixer +{ + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, NoExtraBlankLinesFixer, NoRedundantReadonlyPropertyFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 4; + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_02_00 && $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts readonly comment on classes to the readonly keyword.', + [ + new VersionSpecificCodeSample( + << $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + + $annotations = $doc->getAnnotationsOfType('readonly'); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $annotation->remove(); + } + + $mainIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + $addReadonly = true; + + while ($tokens[$index]->isGivenKind([ + \T_ABSTRACT, + \T_FINAL, + \T_PRIVATE, + \T_PUBLIC, + \T_PROTECTED, + \T_READONLY, + ])) { + if ($tokens[$index]->isGivenKind(\T_READONLY)) { + $addReadonly = false; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(\T_CLASS)) { + continue; + } + + if ($addReadonly) { + $tokens->insertAt($index, [new Token([\T_READONLY, 'readonly']), new Token([\T_WHITESPACE, ' '])]); + } + + $newContent = $doc->getContent(); + + if ('' === $newContent) { + $tokens->clearTokenAndMergeSurroundingWhitespace($mainIndex); + + continue; + } + + $tokens[$mainIndex] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php new file mode 100644 index 0000000..5458b49 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProtectedToPrivateFixer extends AbstractFixer +{ + private const MODIFIER_KINDS = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_NS_SEPARATOR, \T_STRING, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, \T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET]; + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `protected` variables and methods to `private` where possible.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, FCT::T_PROTECTED_SET]) + && ( + $tokens->isAllTokenKindsFound([\T_CLASS, \T_FINAL]) + || $tokens->isTokenKindFound(FCT::T_ENUM) + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + $classesCandidate = []; + $classElementTypes = ['method' => true, 'property' => true, 'promoted_property' => true, 'const' => true]; + + foreach ($this->tokensAnalyzer->getClassyElements() as $index => $element) { + $classIndex = $element['classIndex']; + + $classesCandidate[$classIndex] ??= $this->isClassCandidate($tokens, $classIndex); + + if (false === $classesCandidate[$classIndex]) { + continue; + } + + if (!isset($classElementTypes[$element['type']])) { + continue; + } + + $previousIndex = $index; + $protectedIndex = null; + $protectedPromotedIndex = null; + $protectedSetIndex = null; + $isFinal = false; + + do { + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + + if ($tokens[$previousIndex]->isGivenKind(\T_PROTECTED)) { + $protectedIndex = $previousIndex; + } elseif ($tokens[$previousIndex]->isGivenKind(CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED)) { + $protectedPromotedIndex = $previousIndex; + } elseif ($tokens[$previousIndex]->isGivenKind(FCT::T_PROTECTED_SET)) { + $protectedSetIndex = $previousIndex; + } elseif ($tokens[$previousIndex]->isGivenKind(\T_FINAL)) { + $isFinal = true; + } + } while ($tokens[$previousIndex]->isGivenKind(self::MODIFIER_KINDS)); + + if ($isFinal && 'const' === $element['type']) { + continue; // Final constants cannot be private + } + + if (null !== $protectedIndex) { + $tokens[$protectedIndex] = new Token([\T_PRIVATE, 'private']); + } + if (null !== $protectedPromotedIndex) { + $tokens[$protectedPromotedIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, 'private']); + } + if (null !== $protectedSetIndex) { + $tokens[$protectedSetIndex] = new Token([\T_PRIVATE_SET, 'private(set)']); + } + } + } + + /** + * Consider symbol as candidate for fixing if it's: + * - an Enum (PHP8.1+) + * - a class, which: + * - is not anonymous + * - is final + * - does not use traits + * - does not extend other class. + */ + private function isClassCandidate(Tokens $tokens, int $classIndex): bool + { + if ($tokens[$classIndex]->isGivenKind(FCT::T_ENUM)) { + return true; + } + + if (!$tokens[$classIndex]->isGivenKind(\T_CLASS) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) { + return false; + } + + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex); + + if (!isset($modifiers['final'])) { + return false; + } + + $classNameIndex = $tokens->getNextMeaningfulToken($classIndex); // move to class name as anonymous class is never "final" + $classExtendsIndex = $tokens->getNextMeaningfulToken($classNameIndex); // move to possible "extends" + + if ($tokens[$classExtendsIndex]->isGivenKind(\T_EXTENDS)) { + return false; + } + + if (!$tokens->isTokenKindFound(CT::T_USE_TRAIT)) { + return true; // cheap test + } + + $classOpenIndex = $tokens->getNextTokenOfKind($classNameIndex, ['{']); + $classCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpenIndex); + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + + return null === $useIndex || $useIndex > $classCloseIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php new file mode 100644 index 0000000..0c452e8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SelfAccessorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Inside class or interface element `self` should be preferred to the class name itself.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]); + } + + /** + * {@inheritdoc} + * + * Must run after PsrAutoloadingFixer. + */ + public function getPriority(): int + { + return -11; + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if (!$tokens[$index]->isGivenKind([\T_CLASS, \T_INTERFACE]) || $tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + $nameIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING]]); + $startIndex = $tokens->getNextTokenOfKind($nameIndex, ['{']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $startIndex); + + $name = $tokens[$nameIndex]->getContent(); + + $this->replaceNameOccurrences($tokens, $namespace->getFullName(), $name, $startIndex, $endIndex); + + $index = $endIndex; + } + } + } + + /** + * Replace occurrences of the name of the classy element by "self" (if possible). + */ + private function replaceNameOccurrences(Tokens $tokens, string $namespace, string $name, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $insideMethodSignatureUntil = null; + + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ($i === $insideMethodSignatureUntil) { + $insideMethodSignatureUntil = null; + } + + $token = $tokens[$i]; + + // skip anonymous classes + if ($token->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $i); + + continue; + } + + if ($token->isGivenKind(\T_FN)) { + $i = $tokensAnalyzer->getLastTokenIndexOfArrowFunction($i); + $i = $tokens->getNextMeaningfulToken($i); + + continue; + } + + if ($token->isGivenKind(\T_FUNCTION)) { + if ($tokensAnalyzer->isLambda($i)) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $i); + + continue; + } + + $i = $tokens->getNextTokenOfKind($i, ['(']); + $insideMethodSignatureUntil = $tokens->getNextTokenOfKind($i, ['{', ';']); + + continue; + } + + if (!$token->equals([\T_STRING, $name], false)) { + continue; + } + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($i)]; + if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + $classStartIndex = $i; + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)]; + if ($prevToken->isGivenKind(\T_NS_SEPARATOR)) { + $classStartIndex = $this->getClassStart($tokens, $i, $namespace); + if (null === $classStartIndex) { + continue; + } + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($classStartIndex)]; + } + if ($prevToken->isGivenKind([\T_STRING, \T_PAAMAYIM_NEKUDOTAYIM]) || $prevToken->isObjectOperator()) { + continue; + } + + if ( + $prevToken->isGivenKind([\T_INSTANCEOF, \T_NEW]) + || $nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM) + || ( + null !== $insideMethodSignatureUntil + && $i < $insideMethodSignatureUntil + && $prevToken->equalsAny(['(', ',', [CT::T_NULLABLE_TYPE], [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_COLON]]) + ) + ) { + for ($j = $classStartIndex; $j < $i; ++$j) { + $tokens->clearTokenAndMergeSurroundingWhitespace($j); + } + $tokens[$i] = new Token([\T_STRING, 'self']); + } + } + } + + private function getClassStart(Tokens $tokens, int $index, string $namespace): ?int + { + $namespace = ('' !== $namespace ? '\\'.$namespace : '').'\\'; + + foreach (array_reverse(Preg::split('/(\\\)/', $namespace, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE)) as $piece) { + $index = $tokens->getPrevMeaningfulToken($index); + if ('\\' === $piece) { + if (!$tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) { + return null; + } + } elseif (!$tokens[$index]->equals([\T_STRING, $piece], false)) { + return null; + } + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php new file mode 100644 index 0000000..eadbae8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php @@ -0,0 +1,228 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SelfStaticAccessorFixer extends AbstractFixer +{ + private const CLASSY_TYPES = [\T_CLASS, FCT::T_ENUM]; + private const CLASSY_TOKENS_OF_INTEREST = [[\T_CLASS], [FCT::T_ENUM]]; + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Inside an enum or `final`/anonymous class, `self` should be preferred over `static`.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_STATIC) + && $tokens->isAnyTokenKindsFound(self::CLASSY_TYPES) + && $tokens->isAnyTokenKindsFound([\T_DOUBLE_COLON, \T_NEW, \T_INSTANCEOF]); + } + + /** + * {@inheritdoc} + * + * Must run after FinalClassFixer, FinalInternalClassFixer, FunctionToConstantFixer, PhpUnitTestCaseStaticMethodCallsFixer. + */ + public function getPriority(): int + { + return -10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + $classyIndex = $tokens->getNextTokenOfKind(0, self::CLASSY_TOKENS_OF_INTEREST); + + while (null !== $classyIndex) { + if ($tokens[$classyIndex]->isGivenKind(\T_CLASS)) { + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classyIndex); + + if ( + isset($modifiers['final']) + || $this->tokensAnalyzer->isAnonymousClass($classyIndex) + ) { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + } else { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + + $classyIndex = $tokens->getNextTokenOfKind($classyIndex, self::CLASSY_TOKENS_OF_INTEREST); + } + } + + private function fixClassy(Tokens $tokens, int $index): int + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $classOpenCount = 1; + + while ($classOpenCount > 0) { + ++$index; + + if ($tokens[$index]->equals('{')) { + ++$classOpenCount; + + continue; + } + + if ($tokens[$index]->equals('}')) { + --$classOpenCount; + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + // do not fix inside lambda + if ($this->tokensAnalyzer->isLambda($index)) { + // figure out where the lambda starts + $index = $tokens->getNextTokenOfKind($index, ['{']); + $openCount = 1; + + do { + $index = $tokens->getNextTokenOfKind($index, ['}', '{', [\T_CLASS]]); + if ($tokens[$index]->equals('}')) { + --$openCount; + } elseif ($tokens[$index]->equals('{')) { + ++$openCount; + } else { + $index = $this->fixClassy($tokens, $index); + } + } while ($openCount > 0); + } + + continue; + } + + if ($tokens[$index]->isGivenKind([\T_NEW, \T_INSTANCEOF])) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_STATIC)) { + $tokens[$index] = new Token([\T_STRING, 'self']); + } + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_STATIC)) { + continue; + } + + $staticIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + continue; + } + + $tokens[$staticIndex] = new Token([\T_STRING, 'self']); + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php new file mode 100644 index 0000000..9af540d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php @@ -0,0 +1,263 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶4.2. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: list<'const'|'property'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: list<'const'|'property'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Javier Spagnoletti + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority(): int + { + return 56; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be more than one property or constant declared per statement.', + [ + new CodeSample( + <<<'PHP' + ['property']], + ), + ], + ); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + $elements = array_reverse($analyzer->getClassyElements(), true); + + foreach ($elements as $index => $element) { + if (!\in_array($element['type'], $this->configuration['elements'], true)) { + continue; // not in configuration + } + + $this->fixElement($tokens, $element['type'], $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $values = ['const', 'property']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'List of strings which element should be modified.')) + ->setDefault($values) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($values)]) + ->getOption(), + ]); + } + + private function fixElement(Tokens $tokens, string $type, int $index): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $repeatIndex = $index; + + while (true) { + $repeatIndex = $tokens->getNextMeaningfulToken($repeatIndex); + $repeatToken = $tokens[$repeatIndex]; + + if ($tokensAnalyzer->isArray($repeatIndex)) { + if ($repeatToken->isGivenKind(\T_ARRAY)) { + $repeatIndex = $tokens->getNextTokenOfKind($repeatIndex, ['(']); + $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $repeatIndex); + } else { + $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $repeatIndex); + } + + continue; + } + + if ($repeatToken->equalsAny([';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]])) { + return; // no repeating found, no fixing needed + } + + if ($repeatToken->equals(',')) { + break; + } + } + + $start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']); + $this->expandElement( + $tokens, + $type, + $tokens->getNextMeaningfulToken($start), + $tokens->getNextTokenOfKind($index, [';']), + ); + } + + private function expandElement(Tokens $tokens, string $type, int $startIndex, int $endIndex): void + { + $divisionContent = null; + + if ($tokens[$startIndex - 1]->isWhitespace()) { + $divisionContent = $tokens[$startIndex - 1]->getContent(); + + if (Preg::match('#(\n|\r\n)#', $divisionContent, $matches)) { + $divisionContent = $matches[0].trim($divisionContent, "\r\n"); + } + } + + // iterate variables to split up + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + $token = $tokens[$i]; + + if ($token->equals(')')) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $i); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_CLOSE)) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $i); + + continue; + } + + if (!$tokens[$i]->equals(',')) { + continue; + } + + $tokens[$i] = new Token(';'); + + if ($tokens[$i + 1]->isWhitespace()) { + $tokens->clearAt($i + 1); + } + + if (null !== $divisionContent && '' !== $divisionContent) { + $tokens->insertAt($i + 1, new Token([\T_WHITESPACE, $divisionContent])); + } + + // collect modifiers + $sequence = 'const' === $type + ? $this->getConstantModifiersSequence($tokens, $startIndex) + : $this->getPropertyModifiersSequence($tokens, $startIndex, $endIndex); + $tokens->insertAt($i + 2, $sequence); + } + } + + /** + * @return list + */ + private function getConstantModifiersSequence(Tokens $tokens, int $startIndex): array + { + $assignmentIndex = $tokens->getNextTokenOfKind($startIndex, ['=']); + \assert(\is_int($assignmentIndex)); + + $nameIndex = $tokens->getPrevMeaningfulToken($assignmentIndex); + \assert(\is_int($nameIndex)); + + $sequence = []; + + for ($i = $startIndex; $i < $nameIndex; ++$i) { + if (!$tokens[$i]->isComment()) { + $sequence[] = clone $tokens[$i]; + } + } + + return $sequence; + } + + /** + * @return list + */ + private function getPropertyModifiersSequence(Tokens $tokens, int $startIndex, int $endIndex): array + { + $tokenKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_STATIC, \T_VAR, \T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + $sequence = []; + + for ($i = $startIndex; $i < $endIndex - 1; ++$i) { + if ($tokens[$i]->isComment()) { + continue; + } + + if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isGivenKind($tokenKinds)) { + break; + } + + $sequence[] = clone $tokens[$i]; + } + + return $sequence; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php new file mode 100644 index 0000000..3df3280 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleTraitInsertPerStatementFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each trait `use` must be done as single statement.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(CT::T_USE_TRAIT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 1 < $index; --$index) { + if ($tokens[$index]->isGivenKind(CT::T_USE_TRAIT)) { + $candidates = $this->getCandidates($tokens, $index); + if (\count($candidates) > 0) { + $this->fixTraitUse($tokens, $index, $candidates); + } + } + } + } + + /** + * @param list $candidates ',' indices to fix + */ + private function fixTraitUse(Tokens $tokens, int $useTraitIndex, array $candidates): void + { + foreach ($candidates as $commaIndex) { + $inserts = [ + new Token([CT::T_USE_TRAIT, 'use']), + new Token([\T_WHITESPACE, ' ']), + ]; + + $nextImportStartIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($tokens[$nextImportStartIndex - 1]->isWhitespace()) { + if (Preg::match('/\R/', $tokens[$nextImportStartIndex - 1]->getContent())) { + array_unshift($inserts, clone $tokens[$useTraitIndex - 1]); + } + $tokens->clearAt($nextImportStartIndex - 1); + } + + $tokens[$commaIndex] = new Token(';'); + $tokens->insertAt($nextImportStartIndex, $inserts); + } + } + + /** + * @return list + */ + private function getCandidates(Tokens $tokens, int $index): array + { + $indices = []; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->equals('{')) { + return []; // do not fix use cases with grouping + } + + $indices[] = $index; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + } + + return array_reverse($indices); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StaticPrivateMethodFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StaticPrivateMethodFixer.php new file mode 100644 index 0000000..176f63b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StaticPrivateMethodFixer.php @@ -0,0 +1,281 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StaticPrivateMethodFixer extends AbstractFixer +{ + /** + * @var array + */ + private const MAGIC_METHODS = [ + '__clone' => true, + '__construct' => true, + '__destruct' => true, + '__wakeup' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts private methods to `static` where possible.', + [ + new CodeSample( + <<<'PHP' + baz(); + } + + private function baz() + { + return 1; + } + } + + PHP, + ), + ], + null, + 'Risky when the method:' + .' contains dynamic generated calls to the instance,' + .' is dynamically referenced,' + .' is referenced inside a Trait the class uses.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before StaticLambdaFixer. + * Must run after ProtectedToPrivateFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_PRIVATE, \T_FUNCTION]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + do { + $anythingChanged = false; + + $end = \count($tokens) - 3; // min. number of tokens to form a class candidate to fix + for ($index = $end; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS)) { + continue; + } + + $classOpen = $tokens->getNextTokenOfKind($index, ['{']); + $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpen); + + $anythingChanged |= $this->fixClass($tokens, $tokensAnalyzer, $classOpen, $classClose); + } + } while ($anythingChanged); + } + + private function fixClass(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $classOpen, int $classClose): bool + { + $fixedMethods = []; + foreach ($this->getClassMethods($tokens, $classOpen, $classClose) as $methodData) { + [$functionKeywordIndex, $methodOpen, $methodClose] = $methodData; + + if ($this->skipMethod($tokens, $tokensAnalyzer, $functionKeywordIndex, $methodOpen, $methodClose)) { + continue; + } + + $methodNameIndex = $tokens->getNextMeaningfulToken($functionKeywordIndex); + $methodName = $tokens[$methodNameIndex]->getContent(); + $fixedMethods[$methodName] = true; + + $tokens->insertSlices([$functionKeywordIndex => [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])]]); + } + + if (0 === \count($fixedMethods)) { + return false; + } + + $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpen); + foreach ($this->getClassMethods($tokens, $classOpen, $classClose) as $methodData) { + [, $methodOpen, $methodClose] = $methodData; + + $this->fixReferencesInFunction($tokens, $tokensAnalyzer, $methodOpen, $methodClose, $fixedMethods); + } + + return true; + } + + private function skipMethod(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $functionKeywordIndex, int $methodOpen, int $methodClose): bool + { + $methodNameIndex = $tokens->getNextMeaningfulToken($functionKeywordIndex); + $methodName = strtolower($tokens[$methodNameIndex]->getContent()); + if (isset(self::MAGIC_METHODS[$methodName])) { + return true; + } + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($functionKeywordIndex); + if ($tokens[$prevTokenIndex]->isGivenKind(\T_FINAL)) { + $prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); + } + if (!$tokens[$prevTokenIndex]->isGivenKind(\T_PRIVATE)) { + return true; + } + + $prePrevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); + if ($tokens[$prePrevTokenIndex]->isGivenKind(\T_STATIC)) { + return true; + } + + for ($index = $methodOpen + 1; $index < $methodClose - 1; ++$index) { + if ($tokens[$index]->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { + $anonymousClassOpen = $tokens->getNextTokenOfKind($index, ['{']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $anonymousClassOpen); + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + return true; + } + + if ($tokens[$index]->equals([\T_VARIABLE, '$this'])) { + $operatorIndex = $tokens->getNextMeaningfulToken($index); + $methodNameIndex = $tokens->getNextMeaningfulToken($operatorIndex); + $argumentsBraceIndex = $tokens->getNextMeaningfulToken($methodNameIndex); + + if ( + !$tokens[$operatorIndex]->isGivenKind(\T_OBJECT_OPERATOR) + || $methodName !== $tokens[$methodNameIndex]->getContent() + || !$tokens[$argumentsBraceIndex]->equals('(') + ) { + return true; + } + } + + if ($tokens[$index]->equals([\T_STRING, 'debug_backtrace'])) { + return true; + } + } + + return false; + } + + /** + * @param array $fixedMethods + */ + private function fixReferencesInFunction(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $methodOpen, int $methodClose, array $fixedMethods): void + { + for ($index = $methodOpen + 1; $index < $methodClose - 1; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $closureStart = $tokens->getNextTokenOfKind($index, ['{']); + $closureEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $closureStart); + if (!$tokens[$prevIndex]->isGivenKind(\T_STATIC)) { + $this->fixReferencesInFunction($tokens, $tokensAnalyzer, $closureStart, $closureEnd, $fixedMethods); + } + + $index = $closureEnd; + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { + $anonymousClassOpen = $tokens->getNextTokenOfKind($index, ['{']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $anonymousClassOpen); + + continue; + } + + if (!$tokens[$index]->equals([\T_VARIABLE, '$this'])) { + continue; + } + + $objectOperatorIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$objectOperatorIndex]->isGivenKind(\T_OBJECT_OPERATOR)) { + continue; + } + + $methodNameIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex); + $argumentsBraceIndex = $tokens->getNextMeaningfulToken($methodNameIndex); + if (!$tokens[$argumentsBraceIndex]->equals('(')) { + continue; + } + + $currentMethodName = $tokens[$methodNameIndex]->getContent(); + if (!isset($fixedMethods[$currentMethodName])) { + continue; + } + + $tokens[$index] = new Token([\T_STRING, 'self']); + $tokens[$objectOperatorIndex] = new Token([\T_DOUBLE_COLON, '::']); + } + } + + /** + * @return iterable + */ + private function getClassMethods(Tokens $tokens, int $classOpen, int $classClose): iterable + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $classClose - 1; $index > $classOpen + 1; --$index) { + if ($tokens[$index]->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + if ($tokensAnalyzer->getMethodAttributes($index)['abstract']) { + continue; + } + + $methodOpen = $tokens->getNextTokenOfKind($index, ['{']); + $methodClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $methodOpen); + + yield [$index, $methodOpen, $methodClose]; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StringableForToStringFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StringableForToStringFixer.php new file mode 100644 index 0000000..6a32303 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/StringableForToStringFixer.php @@ -0,0 +1,259 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Santiago San Martin + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StringableForToStringFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A class that implements the `__toString()` method must explicitly implement the `Stringable` interface.', + [ + new CodeSample( + <<<'PHP' + = 8_00_00 && $tokens->isAllTokenKindsFound([\T_CLASS, \T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + $stringableInterfaces = ['stringable']; + + for ($index = 1; $index < $tokens->count(); ++$index) { + if ($tokens[$index]->isGivenKind(\T_NAMESPACE)) { + $stringableInterfaces = []; + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_USE)) { + $name = self::getNameFromUse($index, $useDeclarations); + if (null !== $name) { + $stringableInterfaces[] = $name; + } + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_CLASS)) { + continue; + } + + $classStartIndex = $tokens->getNextTokenOfKind($index, ['{']); + \assert(\is_int($classStartIndex)); + + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classStartIndex); + + if (!self::doesHaveToStringMethod($tokens, $classStartIndex, $classEndIndex)) { + continue; + } + + if (self::doesImplementStringable($tokens, $index, $classStartIndex, $stringableInterfaces)) { + continue; + } + + self::addStringableInterface($tokens, $index); + } + } + + /** + * @param list $useDeclarations + */ + private static function getNameFromUse(int $index, array $useDeclarations): ?string + { + $uses = array_filter( + $useDeclarations, + static fn (NamespaceUseAnalysis $namespaceUseAnalysis): bool => $namespaceUseAnalysis->getStartIndex() === $index, + ); + + if (0 === \count($uses)) { + return null; + } + + \assert(1 === \count($uses)); + + $useDeclaration = reset($uses); + + $lowercasedFullName = strtolower($useDeclaration->getFullName()); + if ('stringable' !== $lowercasedFullName && '\stringable' !== $lowercasedFullName) { + return null; + } + + return strtolower($useDeclaration->getShortName()); + } + + private static function doesHaveToStringMethod(Tokens $tokens, int $classStartIndex, int $classEndIndex): bool + { + $index = $classStartIndex; + + while ($index < $classEndIndex) { + ++$index; + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + \assert(\is_int($functionNameIndex)); + + if ($tokens[$functionNameIndex]->equals([\T_STRING, '__toString'], false)) { + return true; + } + } + + return false; + } + + /** + * @param list $stringableInterfaces + */ + private static function doesImplementStringable( + Tokens $tokens, + int $classKeywordIndex, + int $classOpenBraceIndex, + array $stringableInterfaces + ): bool { + $implementedInterfaces = self::getInterfaces($tokens, $classKeywordIndex, $classOpenBraceIndex); + if ([] === $implementedInterfaces) { + return false; + } + if (\in_array('\stringable', $implementedInterfaces, true)) { + return true; + } + + foreach ($stringableInterfaces as $stringableInterface) { + if (\in_array($stringableInterface, $implementedInterfaces, true)) { + return true; + } + } + + return false; + } + + /** + * @return list + */ + private static function getInterfaces(Tokens $tokens, int $classKeywordIndex, int $classOpenBraceIndex): array + { + $implementsIndex = $tokens->getNextTokenOfKind($classKeywordIndex, ['{', [\T_IMPLEMENTS]]); + \assert(\is_int($implementsIndex)); + + $interfaces = []; + $interface = ''; + for ( + $index = $tokens->getNextMeaningfulToken($implementsIndex); + $index < $classOpenBraceIndex; + $index = $tokens->getNextMeaningfulToken($index) + ) { + \assert(\is_int($index)); + if ($tokens[$index]->equals(',')) { + $interfaces[] = strtolower($interface); + $interface = ''; + + continue; + } + $interface .= $tokens[$index]->getContent(); + } + if ('' !== $interface) { + $interfaces[] = strtolower($interface); + } + + return $interfaces; + } + + private static function addStringableInterface(Tokens $tokens, int $classIndex): void + { + $implementsIndex = $tokens->getNextTokenOfKind($classIndex, ['{', [\T_IMPLEMENTS]]); + \assert(\is_int($implementsIndex)); + + if ($tokens[$implementsIndex]->equals('{')) { + $prevIndex = $tokens->getPrevMeaningfulToken($implementsIndex); + \assert(\is_int($prevIndex)); + + $tokens->insertSlices([ + $prevIndex + 1 => [ + new Token([\T_WHITESPACE, ' ']), + new Token([\T_IMPLEMENTS, 'implements']), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, \Stringable::class]), + ], + ]); + + return; + } + + $afterImplementsIndex = $tokens->getNextMeaningfulToken($implementsIndex); + \assert(\is_int($afterImplementsIndex)); + + $tokens->insertSlices([ + $afterImplementsIndex => [ + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, \Stringable::class]), + new Token(','), + new Token([\T_WHITESPACE, ' ']), + ], + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php new file mode 100644 index 0000000..7a808ee --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: list<'const'|'method'|'property'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: list<'const'|'method'|'property'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class VisibilityRequiredFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private ModifierKeywordsFixer $proxyFixer; + + public function __construct() + { + $this->proxyFixer = new ModifierKeywordsFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->proxyFixer->getDefinition(); + + return new FixerDefinition( + $fixerDefinition->getSummary(), + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + protected function createProxyFixers(): array + { + return [ + $this->proxyFixer, + ]; + } + + /** + * @param _AutogeneratedInputConfiguration $configuration + */ + protected function configurePreNormalisation(array $configuration): void + { + $this->proxyFixer->configure($configuration); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return $this->proxyFixer->createConfigurationDefinition(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php new file mode 100644 index 0000000..d77ee4d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php @@ -0,0 +1,148 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ClassUsage; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DateTimeImmutableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Class `DateTimeImmutable` should be used instead of `DateTime`.', + [new CodeSample("isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $functionMap = [ + 'date_create' => 'date_create_immutable', + 'date_create_from_format' => 'date_create_immutable_from_format', + ]; + + $isInNamespace = false; + $isImported = false; // e.g. use DateTime; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_NAMESPACE)) { + $isInNamespace = true; + + continue; + } + + if ($isInNamespace && $token->isGivenKind(\T_USE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ('datetime' !== strtolower($tokens[$nextIndex]->getContent())) { + continue; + } + + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if ($tokens[$nextNextIndex]->equals(';')) { + $isImported = true; + } + + $index = $nextNextIndex; + + continue; + } + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $lowercaseContent = strtolower($token->getContent()); + + if ('datetime' === $lowercaseContent) { + $this->fixClassUsage($tokens, $index, $isInNamespace, $isImported); + $limit = $tokens->count(); // update limit, as fixing class usage may insert new token + + continue; + } + + if (isset($functionMap[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $tokens[$index] = new Token([\T_STRING, $functionMap[$lowercaseContent]]); + } + } + } + + private function fixClassUsage(Tokens $tokens, int $index, bool $isInNamespace, bool $isImported): void + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_DOUBLE_COLON)) { + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + if ($tokens[$nextNextIndex]->isGivenKind(\T_STRING)) { + $nextNextNextIndex = $tokens->getNextMeaningfulToken($nextNextIndex); + if (!$tokens[$nextNextNextIndex]->equals('(')) { + return; + } + } + } + + $isUsedAlone = false; // e.g. new DateTime(); + $isUsedWithLeadingBackslash = false; // e.g. new \DateTime(); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$prevPrevIndex]->isGivenKind(\T_STRING)) { + $isUsedWithLeadingBackslash = true; + } + } elseif (!$tokens[$prevIndex]->isGivenKind(\T_DOUBLE_COLON) && !$tokens[$prevIndex]->isObjectOperator()) { + $isUsedAlone = true; + } + + if ($isUsedWithLeadingBackslash || $isUsedAlone && ($isInNamespace && $isImported || !$isInNamespace)) { + $tokens[$index] = new Token([\T_STRING, \DateTimeImmutable::class]); + if ($isInNamespace && $isUsedAlone) { + $tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\'])); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php new file mode 100644 index 0000000..bf0f10f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php @@ -0,0 +1,236 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ignored_tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ignored_tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CommentToPhpdocFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var list + */ + private array $ignoredTags = []; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after AlignMultilineCommentFixer. + */ + public function getPriority(): int + { + // Should be run before all other PHPDoc fixers + return 26; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Comments with annotation should be docblock when used on structural elements.', + [ + new CodeSample(" ['todo']]), + ], + null, + 'Risky as new docblocks might mean more, e.g. a Doctrine entity might have a new column in database.', + ); + } + + protected function configurePostNormalisation(): void + { + $this->ignoredTags = array_map( + static fn (string $tag): string => strtolower($tag), + $this->configuration['ignored_tags'], + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of ignored tags.')) + ->setAllowedTypes(['string[]']) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $commentsAnalyzer = new CommentsAnalyzer(); + + for ($index = 0, $limit = \count($tokens); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_COMMENT)) { + continue; + } + + if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { + continue; + } + + if (!$commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { + continue; + } + + if (Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@(?=\w+-(ignore|suppress))([a-zA-Z0-9_\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent())) { + continue; + } + + $commentIndices = $commentsAnalyzer->getCommentBlockIndices($tokens, $index); + + if ($this->isCommentCandidate($tokens, $commentIndices)) { + $this->fixComment($tokens, $commentIndices); + } + + $index = max($commentIndices); + } + } + + /** + * @param list $indices + */ + private function isCommentCandidate(Tokens $tokens, array $indices): bool + { + return array_reduce( + $indices, + function (bool $carry, int $index) use ($tokens): bool { + if ($carry) { + return true; + } + if (!Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@([a-zA-Z0-9_\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent(), $matches)) { + return false; + } + + return !\in_array(strtolower($matches[1]), $this->ignoredTags, true); + }, + false, + ); + } + + /** + * @param non-empty-list $indices + */ + private function fixComment(Tokens $tokens, array $indices): void + { + if (1 === \count($indices)) { + $this->fixCommentSingleLine($tokens, $indices[0]); + } else { + $this->fixCommentMultiLine($tokens, $indices); + } + } + + private function fixCommentSingleLine(Tokens $tokens, int $index): void + { + $message = $this->getMessage($tokens[$index]->getContent()); + + if ('' !== trim(substr($message, 0, 1))) { + $message = ' '.$message; + } + + if ('' !== trim(substr($message, -1))) { + $message .= ' '; + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, '/**'.$message.'*/']); + } + + /** + * @param non-empty-list $indices + */ + private function fixCommentMultiLine(Tokens $tokens, array $indices): void + { + $startIndex = $indices[0]; + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$startIndex - 1]); + + $newContent = '/**'.$this->whitespacesConfig->getLineEnding(); + $count = max($indices); + + for ($index = $startIndex; $index <= $count; ++$index) { + if (!$tokens[$index]->isComment()) { + continue; + } + if (str_contains($tokens[$index]->getContent(), '*/')) { + return; + } + $message = $this->getMessage($tokens[$index]->getContent()); + if ('' !== trim(substr($message, 0, 1))) { + $message = ' '.$message; + } + $newContent .= $indent.' *'.$message.$this->whitespacesConfig->getLineEnding(); + } + + for ($index = $startIndex; $index <= $count; ++$index) { + $tokens->clearAt($index); + } + + $newContent .= $indent.' */'; + + $tokens->insertAt($startIndex, new Token([\T_DOC_COMMENT, $newContent])); + } + + private function getMessage(string $content): string + { + if (str_starts_with($content, '#')) { + return substr($content, 1); + } + if (str_starts_with($content, '//')) { + return substr($content, 2); + } + + return rtrim(ltrim($content, '/*'), '*/'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php new file mode 100644 index 0000000..e3cf0f6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php @@ -0,0 +1,550 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\PregException; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * comment_type?: 'PHPDoc'|'comment', + * header: string, + * location?: 'after_declare_strict'|'after_open', + * separate?: 'both'|'bottom'|'none'|'top', + * validator?: null|string, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * comment_type: 'PHPDoc'|'comment', + * header: string, + * location: 'after_declare_strict'|'after_open', + * separate: 'both'|'bottom'|'none'|'top', + * validator: null|string, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Antonio J. García Lagar + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class HeaderCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const HEADER_PHPDOC = 'PHPDoc'; + + /** + * @internal + */ + public const HEADER_COMMENT = 'comment'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add, replace or remove header comment.', + [ + new CodeSample( + <<<'PHP' + 'Made with love.', + ], + ), + new CodeSample( + <<<'PHP' + 'Made with love.', + 'comment_type' => self::HEADER_PHPDOC, + 'location' => 'after_open', + 'separate' => 'bottom', + ], + ), + new CodeSample( + <<<'PHP' + 'Made with love.', + 'comment_type' => self::HEADER_COMMENT, + 'location' => 'after_declare_strict', + ], + ), + new CodeSample( + <<<'PHP' + 'Made with love.', + 'validator' => '/Made with love(?P.*)??/s', + 'comment_type' => self::HEADER_COMMENT, + 'location' => 'after_declare_strict', + ], + ), + new CodeSample( + <<<'PHP' + '', + ], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLinesBeforeNamespaceFixer, SingleBlankLineBeforeNamespaceFixer, SingleLineCommentStyleFixer. + * Must run after DeclareStrictTypesFixer, NoBlankLinesAfterPhpdocFixer. + */ + public function getPriority(): int + { + // When this fixer is configured with ["separate" => "bottom", "comment_type" => "PHPDoc"] + // and the target file has no namespace or declare() construct, + // the fixed header comment gets trimmed by NoBlankLinesAfterPhpdocFixer if we run before it. + return -30; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $headerAsComment = $this->getHeaderAsComment(); + $location = $this->configuration['location']; + $locationIndices = []; + + foreach (['after_open', 'after_declare_strict'] as $possibleLocation) { + $locationIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + + if (!isset($locationIndices[$locationIndex]) || $possibleLocation === $location) { + $locationIndices[$locationIndex] = $possibleLocation; + } + } + + // pre-run to find existing comment, if dynamic content is allowed + if (null !== $this->configuration['validator']) { + foreach ($locationIndices as $possibleLocation) { + // figure out where the comment should be placed + $headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + + // check if there is already a comment + $headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerAsComment, $headerNewIndex - 1); + + if (null === $headerCurrentIndex) { + continue; + } + $currentHeaderComment = $tokens[$headerCurrentIndex]->getContent(); + + if ($this->doesTokenFulfillValidator($tokens[$headerCurrentIndex])) { + $headerAsComment = $currentHeaderComment; + } + } + } + + foreach ($locationIndices as $possibleLocation) { + // figure out where the comment should be placed + $headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + + // check if there is already a comment + $headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerAsComment, $headerNewIndex - 1); + + if (null === $headerCurrentIndex) { + if ('' === $this->configuration['header'] || $possibleLocation !== $location) { + continue; + } + + $this->insertHeader($tokens, $headerAsComment, $headerNewIndex); + + continue; + } + + $currentHeaderComment = $tokens[$headerCurrentIndex]->getContent(); + $sameComment = $headerAsComment === $currentHeaderComment; + $expectedLocation = $possibleLocation === $location; + + if (!$sameComment || !$expectedLocation) { + if ($expectedLocation xor $sameComment) { + $this->removeHeader($tokens, $headerCurrentIndex); + } + + if ('' === $this->configuration['header']) { + continue; + } + + if ($possibleLocation === $location) { + $this->insertHeader($tokens, $headerAsComment, $headerNewIndex); + } + + continue; + } + + $this->fixWhiteSpaceAroundHeader($tokens, $headerCurrentIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $fixerName = $this->getName(); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('header', 'Proper header content.')) + ->setAllowedTypes(['string']) + ->setNormalizer(static function (Options $options, string $value) use ($fixerName): string { + if ('' === trim($value)) { + return ''; + } + + if (str_contains($value, '*/')) { + throw new InvalidFixerConfigurationException($fixerName, 'Cannot use \'*/\' in header.'); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('validator', 'RegEx validator for header content.')) + ->setAllowedTypes(['string', 'null']) + ->setNormalizer(static function (Options $options, ?string $value) use ($fixerName): ?string { + if (null !== $value) { + try { + Preg::match($value, ''); + } catch (PregException $exception) { + throw new InvalidFixerConfigurationException($fixerName, 'Provided RegEx is not valid.'); + } + } + + return $value; + }) + ->setDefault(null) + ->getOption(), + (new FixerOptionBuilder('comment_type', 'Comment syntax type.')) + ->setAllowedValues([self::HEADER_PHPDOC, self::HEADER_COMMENT]) + ->setDefault(self::HEADER_COMMENT) + ->getOption(), + (new FixerOptionBuilder('location', 'The location of the inserted header.')) + ->setAllowedValues(['after_open', 'after_declare_strict']) + ->setDefault('after_declare_strict') + ->getOption(), + (new FixerOptionBuilder('separate', 'Whether the header should be separated from the file content with a new line.')) + ->setAllowedValues(['both', 'top', 'bottom', 'none']) + ->setDefault('both') + ->getOption(), + ]); + } + + private function doesTokenFulfillValidator(Token $token): bool + { + if (null === $this->configuration['validator']) { + throw new \LogicException(\sprintf("Cannot call '%s' method while missing config:validator.", __METHOD__)); + } + $currentHeaderComment = $token->getContent(); + + $lines = implode("\n", array_map( + static fn (string $line): string => ' *' === $line ? '' : (str_starts_with($line, ' * ') ? substr($line, 3) : $line), + \array_slice(explode("\n", $currentHeaderComment), 1, -1), + )); + + return Preg::match($this->configuration['validator'], $lines); + } + + /** + * Enclose the given text in a comment block. + */ + private function getHeaderAsComment(): string + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $comment = (self::HEADER_COMMENT === $this->configuration['comment_type'] ? '/*' : '/**').$lineEnding; + $lines = explode("\n", str_replace("\r", '', $this->configuration['header'])); + + foreach ($lines as $line) { + $comment .= rtrim(' * '.$line).$lineEnding; + } + + return $comment.' */'; + } + + private function findHeaderCommentCurrentIndex(Tokens $tokens, string $headerAsComment, int $headerNewIndex): ?int + { + $index = $tokens->getNextNonWhitespace($headerNewIndex); + + if (null === $index || !$tokens[$index]->isComment()) { + return null; + } + + $next = $index + 1; + + if (!isset($tokens[$next]) || \in_array($this->configuration['separate'], ['top', 'none'], true) || !$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + return $index; + } + + if ($tokens[$next]->isWhitespace()) { + if (!Preg::match('/^\h*\R\h*$/D', $tokens[$next]->getContent())) { + return $index; + } + + ++$next; + } + + if (!isset($tokens[$next]) || !$tokens[$next]->isClassy() && !$tokens[$next]->isGivenKind(\T_FUNCTION)) { + return $index; + } + + if ( + $headerAsComment === $tokens[$index]->getContent() + || (null !== $this->configuration['validator'] && $this->doesTokenFulfillValidator($tokens[$index])) + ) { + return $index; + } + + return null; + } + + /** + * Find the index where the header comment must be inserted. + */ + private function findHeaderCommentInsertionIndex(Tokens $tokens, string $location): int + { + $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0; + + if ('after_open' === $location) { + return $openTagIndex + 1; + } + + $index = $tokens->getNextMeaningfulToken($openTagIndex); + + if (null === $index) { + return $openTagIndex + 1; // file without meaningful tokens but an open tag, comment should always be placed directly after the open tag + } + + if (!$tokens[$index]->isGivenKind(\T_DECLARE)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($index); + + if (null === $next || !$tokens[$next]->equals('(')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals([\T_STRING, 'strict_types'], false)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals('=')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->isGivenKind(\T_LNUMBER)) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals(')')) { + return $openTagIndex + 1; + } + + $next = $tokens->getNextMeaningfulToken($next); + + if (null === $next || !$tokens[$next]->equals(';')) { // don't insert after close tag + return $openTagIndex + 1; + } + + return $next + 1; + } + + private function fixWhiteSpaceAroundHeader(Tokens $tokens, int $headerIndex): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + // fix lines after header comment + if ( + ('both' === $this->configuration['separate'] || 'bottom' === $this->configuration['separate']) + && null !== $tokens->getNextMeaningfulToken($headerIndex) + ) { + $expectedLineCount = 2; + } else { + $expectedLineCount = 1; + } + + if ($headerIndex === \count($tokens) - 1) { + $tokens->insertAt($headerIndex + 1, new Token([\T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount)])); + } else { + $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, 1); + + if ($lineBreakCount < $expectedLineCount) { + $missing = str_repeat($lineEnding, $expectedLineCount - $lineBreakCount); + + if ($tokens[$headerIndex + 1]->isWhitespace()) { + $tokens[$headerIndex + 1] = new Token([\T_WHITESPACE, $missing.$tokens[$headerIndex + 1]->getContent()]); + } else { + $tokens->insertAt($headerIndex + 1, new Token([\T_WHITESPACE, $missing])); + } + } elseif ($lineBreakCount > $expectedLineCount && $tokens[$headerIndex + 1]->isWhitespace()) { + $newLinesToRemove = $lineBreakCount - $expectedLineCount; + $tokens[$headerIndex + 1] = new Token([ + \T_WHITESPACE, + Preg::replace("/^\\R{{$newLinesToRemove}}/", '', $tokens[$headerIndex + 1]->getContent()), + ]); + } + } + + // fix lines before header comment + $expectedLineCount = 'both' === $this->configuration['separate'] || 'top' === $this->configuration['separate'] ? 2 : 1; + $prev = $tokens->getPrevNonWhitespace($headerIndex); + + $regex = '/\h$/'; + + if ($tokens[$prev]->isGivenKind(\T_OPEN_TAG) && Preg::match($regex, $tokens[$prev]->getContent())) { + $tokens[$prev] = new Token([\T_OPEN_TAG, Preg::replace($regex, $lineEnding, $tokens[$prev]->getContent())]); + } + + $lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, -1); + + if ($lineBreakCount < $expectedLineCount) { + // because of the way the insert index was determined for header comment there cannot be an empty token here + $tokens->insertAt($headerIndex, new Token([\T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount - $lineBreakCount)])); + } + } + + private function getLineBreakCount(Tokens $tokens, int $index, int $direction): int + { + $whitespace = ''; + + for ($index += $direction; isset($tokens[$index]); $index += $direction) { + $token = $tokens[$index]; + + if ($token->isWhitespace()) { + $whitespace .= $token->getContent(); + + continue; + } + + if (-1 === $direction && $token->isGivenKind(\T_OPEN_TAG)) { + $whitespace .= $token->getContent(); + } + + if ('' !== $token->getContent()) { + break; + } + } + + return substr_count($whitespace, "\n"); + } + + private function removeHeader(Tokens $tokens, int $index): void + { + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + $newlineRemoved = false; + + if ($prevToken->isWhitespace()) { + $content = $prevToken->getContent(); + + if (Preg::match('/\R/', $content)) { + $newlineRemoved = true; + } + + $content = Preg::replace('/\R?\h*$/', '', $content); + + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content); + } + + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex] ?? null; + + if (!$newlineRemoved && null !== $nextToken && $nextToken->isWhitespace()) { + $content = Preg::replace('/^\R/', '', $nextToken->getContent()); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + private function insertHeader(Tokens $tokens, string $headerAsComment, int $index): void + { + $tokens->insertAt($index, new Token([self::HEADER_COMMENT === $this->configuration['comment_type'] ? \T_COMMENT : \T_DOC_COMMENT, $headerAsComment])); + $this->fixWhiteSpaceAroundHeader($tokens, $index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php new file mode 100644 index 0000000..6ccb979 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MultilineCommentOpeningClosingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. Both must end with a single asterisk before the closing slash.', + [ + new CodeSample( + <<<'EOT' + isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + $originalContent = $token->getContent(); + + if ( + !$token->isGivenKind(\T_DOC_COMMENT) + && !($token->isGivenKind(\T_COMMENT) && str_starts_with($originalContent, '/*')) + ) { + continue; + } + + $newContent = $originalContent; + + // Fix opening + if ($token->isGivenKind(\T_COMMENT)) { + $newContent = Preg::replace('/^\/\*{2,}(?!\/)/', '/*', $newContent); + } + + // Fix closing + $newContent = Preg::replace('/(?getId(), $newContent]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php new file mode 100644 index 0000000..7c27a4a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoEmptyCommentFixer extends AbstractFixer +{ + private const TYPE_HASH = 1; + + private const TYPE_DOUBLE_SLASH = 2; + + private const TYPE_SLASH_ASTERISK = 3; + + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, NoWhitespaceInEmptyArrayFixer. + * Must run after PhpdocToCommentFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be any empty comments.', + [new CodeSample("isTokenKindFound(\T_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_COMMENT)) { + continue; + } + + $blockInfo = $this->getCommentBlock($tokens, $index); + $blockStart = $blockInfo['blockStart']; + $index = $blockInfo['blockEnd']; + $isEmpty = $blockInfo['isEmpty']; + + if (false === $isEmpty) { + continue; + } + + for ($i = $blockStart; $i <= $index; ++$i) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + + /** + * Return the start index, end index and a flag stating if the comment block is empty. + * + * @param int $index T_COMMENT index + * + * @return array{blockStart: int, blockEnd: int, isEmpty: bool} + */ + private function getCommentBlock(Tokens $tokens, int $index): array + { + $commentType = $this->getCommentType($tokens[$index]->getContent()); + $empty = $this->isEmptyComment($tokens[$index]->getContent()); + + if (self::TYPE_SLASH_ASTERISK === $commentType) { + return [ + 'blockStart' => $index, + 'blockEnd' => $index, + 'isEmpty' => $empty, + ]; + } + + $start = $index; + $count = \count($tokens); + ++$index; + + for (; $index < $count; ++$index) { + if ($tokens[$index]->isComment()) { + if ($commentType !== $this->getCommentType($tokens[$index]->getContent())) { + break; + } + + if ($empty) { // don't retest if already known the block not being empty + $empty = $this->isEmptyComment($tokens[$index]->getContent()); + } + + continue; + } + + if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { + break; + } + } + + return [ + 'blockStart' => $start, + 'blockEnd' => $index - 1, + 'isEmpty' => $empty, + ]; + } + + private function getCommentType(string $content): int + { + if (str_starts_with($content, '#')) { + return self::TYPE_HASH; + } + + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + + return self::TYPE_DOUBLE_SLASH; + } + + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd): int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent()); + } + + return $lineCount; + } + + private function isEmptyComment(string $content): bool + { + $type = $this->getCommentType($content); + \assert(\in_array($type, [self::TYPE_HASH, self::TYPE_SLASH_ASTERISK, self::TYPE_DOUBLE_SLASH], true)); + + return Preg::match([ + self::TYPE_HASH => '|^#\s*$|', // single line comment starting with '#' + self::TYPE_SLASH_ASTERISK => '|^/\*[\s\*]*\*+/$|', // comment starting with '/*' and ending with '*/' (but not a PHPDoc) + self::TYPE_DOUBLE_SLASH => '|^//\s*$|', // single line comment starting with '//' + ][$type], $content); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php new file mode 100644 index 0000000..227649a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no trailing whitespace at the end of lines in comments and PHPDocs.', + [new CodeSample('isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); + + continue; + } + + if ($token->isGivenKind(\T_COMMENT)) { + if (str_starts_with($token->getContent(), '/*')) { + $tokens[$index] = new Token([\T_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]); + } elseif (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { + $trimmedContent = ltrim($tokens[$index + 1]->getContent(), " \t"); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $trimmedContent); + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php new file mode 100644 index 0000000..7128fac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php @@ -0,0 +1,115 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleLineCommentSpacingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line comments must have proper spacing.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $contentLength = \strlen($content); + + if ('/' === $content[0]) { + if ($contentLength < 3) { + continue; // cheap check for "//" + } + + if ('*' === $content[1]) { // slash asterisk comment + if ($contentLength < 5 || '*' === $content[2] || str_contains($content, "\n")) { + continue; // cheap check for "/**/", comment that looks like a PHPDoc, or multi line comment + } + + $newContent = rtrim(substr($content, 0, -2)).' '.substr($content, -2); + $newContent = $this->fixCommentLeadingSpace($newContent, '/*'); + } else { // double slash comment + $newContent = $this->fixCommentLeadingSpace($content, '//'); + } + } else { // hash comment + if ($contentLength < 2 || '[' === $content[1]) { // cheap check for "#" or annotation (like) comment + continue; + } + + $newContent = $this->fixCommentLeadingSpace($content, '#'); + } + + if ($newContent !== $content) { + $tokens[$index] = new Token([\T_COMMENT, $newContent]); + } + } + } + + // fix space between comment open and leading text + private function fixCommentLeadingSpace(string $content, string $prefix): string + { + if (Preg::match(\sprintf('@^%s\h+.*$@', preg_quote($prefix, '@')), $content)) { + return $content; + } + + $position = \strlen($prefix); + + return substr($content, 0, $position).' '.substr($content, $position); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php new file mode 100644 index 0000000..6f828cf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php @@ -0,0 +1,184 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * comment_types?: list<'asterisk'|'hash'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * comment_types: list<'asterisk'|'hash'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleLineCommentStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private bool $asteriskEnabled; + + private bool $hashEnabled; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line comments and multi-line comments with only one line of actual content should use the `//` syntax.', + [ + new CodeSample( + <<<'PHP' + ['asterisk']], + ), + new CodeSample( + " ['hash']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after HeaderCommentFixer, NoUselessReturnFixer, PhpdocToCommentFixer. + */ + public function getPriority(): int + { + return -31; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_COMMENT); + } + + protected function configurePostNormalisation(): void + { + $this->asteriskEnabled = \in_array('asterisk', $this->configuration['comment_types'], true); + $this->hashEnabled = \in_array('hash', $this->configuration['comment_types'], true); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_COMMENT)) { + continue; + } + + $content = $token->getContent(); + + /** @TODO PHP 8.0 - no more need for `?: ''` */ + $commentContent = substr($content, 2, -2) ?: ''; // @phpstan-ignore-line + + if ($this->hashEnabled && str_starts_with($content, '#')) { + if (isset($content[1]) && '[' === $content[1]) { + continue; // This might be an attribute on PHP8, do not change + } + + $tokens[$index] = new Token([$token->getId(), '//'.substr($content, 1)]); + + continue; + } + + if ( + !$this->asteriskEnabled + || str_contains($commentContent, '?>') + || !str_starts_with($content, '/*') + || Preg::match('/[^\s\*].*\R.*[^\s\*]/s', $commentContent) + ) { + continue; + } + + $nextTokenIndex = $index + 1; + if (isset($tokens[$nextTokenIndex])) { + $nextToken = $tokens[$nextTokenIndex]; + if (!$nextToken->isWhitespace() || !Preg::match('/\R/', $nextToken->getContent())) { + continue; + } + + $tokens[$nextTokenIndex] = new Token([$nextToken->getId(), ltrim($nextToken->getContent(), " \t")]); + } + + $content = '//'; + if (Preg::match('/[^\s\*]/', $commentContent)) { + $content = '// '.Preg::replace('/[\s\*]*([^\s\*](?:.+[^\s\*])?)[\s\*]*/', '\1', $commentContent); + } + $tokens[$index] = new Token([$token->getId(), $content]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_types', 'List of comment types to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(['asterisk', 'hash'])]) + ->setDefault(['asterisk', 'hash']) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php new file mode 100644 index 0000000..790d158 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; + +/** + * @template TFixerInputConfig of array + * @template TFixerComputedConfig of array + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ConfigurableFixerInterface extends FixerInterface +{ + /** + * Set configuration. + * + * New configuration must override current one, not patch it. + * Using empty array makes fixer to use default configuration + * (or reset configuration from previously configured back to default one). + * + * Some fixers may have no configuration, then - simply don't implement this interface. + * Other ones may have configuration that will change behaviour of fixer, + * eg `php_unit_strict` fixer allows to configure which methods should be fixed. + * Finally, some fixers need configuration to work, eg `header_comment`. + * + * @param TFixerInputConfig $configuration configuration depends on Fixer + * + * @throws InvalidFixerConfigurationException + */ + public function configure(array $configuration): void; + + /** + * Defines the available configuration options of the fixer. + */ + public function getConfigurationDefinition(): FixerConfigurationResolverInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerTrait.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerTrait.php new file mode 100644 index 0000000..87646a0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerTrait.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException; +use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException; +use PhpCsFixer\Console\Application; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; +use PhpCsFixer\Future; +use Symfony\Component\OptionsResolver\Exception\ExceptionInterface; +use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; + +/** + * @internal + * + * @template TFixerInputConfig of array + * @template TFixerComputedConfig of array + * + * @phpstan-require-implements ConfigurableFixerInterface + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +trait ConfigurableFixerTrait +{ + /** + * @var null|TFixerComputedConfig + */ + protected ?array $configuration = null; + + private ?FixerConfigurationResolverInterface $configurationDefinition = null; + + /** + * @param TFixerInputConfig $configuration + */ + final public function configure(array $configuration): void + { + $this->configurePreNormalisation($configuration); + + foreach ($this->getConfigurationDefinition()->getOptions() as $option) { + if (!$option instanceof DeprecatedFixerOption) { + continue; + } + + $name = $option->getName(); + if (\array_key_exists($name, $configuration)) { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Option "%s" for rule "%s" is deprecated and will be removed in version %d.0. %s', + $name, + $this->getName(), + Application::getMajorVersion() + 1, + str_replace('`', '"', $option->getDeprecationMessage()), + ))); + } + } + + try { + $this->configuration = $this->getConfigurationDefinition()->resolve($configuration); // @phpstan-ignore-line ->configuration typehint is autogenerated base on ConfigurationDefinition + } catch (MissingOptionsException $exception) { + throw new RequiredFixerConfigurationException( + $this->getName(), + \sprintf('Missing required configuration: %s', $exception->getMessage()), + $exception, + ); + } catch (InvalidOptionsForEnvException $exception) { + throw new InvalidForEnvFixerConfigurationException( + $this->getName(), + \sprintf('Invalid configuration for env: %s', $exception->getMessage()), + $exception, + ); + } catch (ExceptionInterface $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + \sprintf('Invalid configuration: %s', $exception->getMessage()), + $exception, + ); + } + + $this->configurePostNormalisation(); + } + + final public function getConfigurationDefinition(): FixerConfigurationResolverInterface + { + if (null === $this->configurationDefinition) { + $this->configurationDefinition = $this->createConfigurationDefinition(); + } + + return $this->configurationDefinition; + } + + abstract public function getName(): string; + + /** + * One can override me. + * + * @param TFixerInputConfig $configuration + */ + protected function configurePreNormalisation(array &$configuration): void + { + // 🤔 ideally this method won't be needed, maybe we can remove it over time + } + + /** + * One can override me. + */ + protected function configurePostNormalisation(): void + { + // 🤔 ideally this method won't be needed, maybe we can remove it over time + } + + abstract protected function createConfigurationDefinition(): FixerConfigurationResolverInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php new file mode 100644 index 0000000..eb82e43 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php @@ -0,0 +1,307 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ConstantNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * exclude?: list, + * fix_built_in?: bool, + * include?: list, + * scope?: 'all'|'namespaced', + * strict?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * exclude: list, + * fix_built_in: bool, + * include: list, + * scope: 'all'|'namespaced', + * strict: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NativeConstantInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private array $constantsToEscape = []; + + /** + * @var array + */ + private array $caseInsensitiveConstantsToEscape = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add leading `\` before constant invocation of internal constant to speed up resolving. Constant name match is case-sensitive, except for `null`, `false` and `true`.', + [ + new CodeSample(" 'namespaced'], + ), + new CodeSample( + " [ + 'MY_CUSTOM_PI', + ], + ], + ), + new CodeSample( + " false, + 'include' => [ + 'MY_CUSTOM_PI', + ], + ], + ), + new CodeSample( + " [ + 'M_PI', + ], + ], + ), + ], + null, + 'Risky when any of the constants are namespaced or overridden.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + * Must run after FunctionToConstantFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $uniqueConfiguredExclude = array_unique($this->configuration['exclude']); + + // Case-sensitive constants handling + $constantsToEscape = array_values($this->configuration['include']); + + if (true === $this->configuration['fix_built_in']) { + $getDefinedConstants = get_defined_constants(true); + unset($getDefinedConstants['user']); + foreach ($getDefinedConstants as $constants) { + $constantsToEscape = [...$constantsToEscape, ...array_keys($constants)]; + } + } + + $constantsToEscape = array_diff( + array_unique($constantsToEscape), + $uniqueConfiguredExclude, + ); + + // Case-insensitive constants handling + $caseInsensitiveConstantsToEscape = []; + + foreach ($constantsToEscape as $constantIndex => $constant) { + $loweredConstant = strtolower($constant); + if (\in_array($loweredConstant, ['null', 'false', 'true'], true)) { + $caseInsensitiveConstantsToEscape[] = $loweredConstant; + unset($constantsToEscape[$constantIndex]); + } + } + + $caseInsensitiveConstantsToEscape = array_diff( + array_unique($caseInsensitiveConstantsToEscape), + array_map( + static fn (string $function): string => strtolower($function), + $uniqueConfiguredExclude, + ), + ); + + // Store the cache + $this->constantsToEscape = array_fill_keys($constantsToEscape, true); + ksort($this->constantsToEscape); + + $this->caseInsensitiveConstantsToEscape = array_fill_keys($caseInsensitiveConstantsToEscape, true); + ksort($this->caseInsensitiveConstantsToEscape); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('all' === $this->configuration['scope']) { + $this->fixConstantInvocations($tokens, 0, \count($tokens) - 1); + + return; + } + + $namespaces = $tokens->getNamespaceDeclarations(); + + // 'scope' is 'namespaced' here + foreach (array_reverse($namespaces) as $namespace) { + if ($namespace->isGlobalNamespace()) { + continue; + } + + $this->fixConstantInvocations($tokens, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex()); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $constantChecker = static function (array $value): bool { + foreach ($value as $constantName) { + if (trim($constantName) !== $constantName) { + throw new InvalidOptionsException(\sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($constantName), + )); + } + } + + return true; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_built_in', 'Whether to fix constants returned by `get_defined_constants`. User constants are not accounted in this list and must be specified in the include one.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('include', 'List of additional constants to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([$constantChecker]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('exclude', 'List of constants to ignore.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([$constantChecker]) + ->setDefault(['null', 'false', 'true']) + ->getOption(), + (new FixerOptionBuilder('scope', 'Only fix constant invocations that are made within a namespace or fix all.')) + ->setAllowedValues(['all', 'namespaced']) + ->setDefault('all') + ->getOption(), + (new FixerOptionBuilder('strict', 'Whether leading `\` of constant invocation not meant to have it should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function fixConstantInvocations(Tokens $tokens, int $startIndex, int $endIndex): void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + $useConstantDeclarations = []; + + foreach ($useDeclarations as $use) { + if ($use->isConstant()) { + $useConstantDeclarations[$use->getShortName()] = true; + } + } + + $tokenAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $endIndex; $index > $startIndex; --$index) { + $token = $tokens[$index]; + + // test if we are at a constant call + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + if (!$tokenAnalyzer->isConstantInvocation($index)) { + continue; + } + + $tokenContent = $token->getContent(); + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!isset($this->constantsToEscape[$tokenContent]) && !isset($this->caseInsensitiveConstantsToEscape[strtolower($tokenContent)])) { + if (false === $this->configuration['strict']) { + continue; + } + + if (!$tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevPrevIndex]->isGivenKind(\T_STRING)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + + continue; + } + + if (isset($useConstantDeclarations[$tokenContent])) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + $tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\'])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php new file mode 100644 index 0000000..81e49b2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php @@ -0,0 +1,220 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ControlStructureBracesFixer extends AbstractFixer +{ + private const CONTROL_TOKENS = [ + \T_DECLARE, + \T_DO, + \T_ELSE, + \T_ELSEIF, + \T_FINALLY, + \T_FOR, + \T_FOREACH, + \T_IF, + \T_WHILE, + \T_TRY, + \T_CATCH, + \T_SWITCH, + ]; + + private const CONTROL_CONTINUATION_TOKENS = [ + \T_IF => [\T_ELSE, \T_ELSEIF], + \T_DO => [\T_WHILE], + \T_TRY => [\T_CATCH, \T_FINALLY], + ]; + + private const FINAL_CONTROL_CONTINUATION_TOKENS = [ + \T_IF => [\T_ELSE], + \T_DO => [], + \T_TRY => [\T_FINALLY], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The body of each control structure MUST be enclosed within braces.', + [new CodeSample("count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(self::CONTROL_TOKENS)) { + continue; + } + + if ( + $token->isGivenKind(\T_ELSE) + && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF) + ) { + continue; + } + + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $nextAfterParenthesisEndIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + $tokenAfterParenthesis = $tokens[$nextAfterParenthesisEndIndex]; + + if ($tokenAfterParenthesis->equalsAny([';', '{', ':', [\T_CLOSE_TAG]])) { + continue; + } + + $statementEndIndex = null; + + if ($tokenAfterParenthesis->isGivenKind([\T_IF, \T_FOR, \T_FOREACH, \T_SWITCH, \T_WHILE])) { + $tokenAfterParenthesisBlockEnd = $tokens->findBlockEnd( // go to ')' + Tokens::BLOCK_TYPE_PARENTHESIS, + $tokens->getNextMeaningfulToken($nextAfterParenthesisEndIndex), + ); + + if ($tokens[$tokens->getNextMeaningfulToken($tokenAfterParenthesisBlockEnd)]->equals(':')) { + $statementEndIndex = $alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $nextAfterParenthesisEndIndex); + + $tokenAfterStatementEndIndex = $tokens->getNextMeaningfulToken($statementEndIndex); + if ($tokens[$tokenAfterStatementEndIndex]->equals(';')) { + $statementEndIndex = $tokenAfterStatementEndIndex; + } + } + } + + if (null === $statementEndIndex) { + $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + } + + $tokensToInsertAfterStatement = [ + new Token([\T_WHITESPACE, ' ']), + new Token('}'), + ]; + + if (!$tokens[$statementEndIndex]->equalsAny([';', '}'])) { + array_unshift($tokensToInsertAfterStatement, new Token(';')); + } + + $tokens->insertSlices([$statementEndIndex + 1 => $tokensToInsertAfterStatement]); + + // insert opening brace + $tokens->insertSlices([$parenthesisEndIndex + 1 => [ + new Token([\T_WHITESPACE, ' ']), + new Token('{'), + ]]); + } + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + if (!$nextToken->equals('(')) { + return $structureTokenIndex; + } + + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + } + + private function findStatementEnd(Tokens $tokens, int $parenthesisEndIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + \assert(\is_int($nextIndex)); + + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->equals('{')) { + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $nextIndex); + } + + if ($nextToken->isGivenKind(self::CONTROL_TOKENS)) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); + + $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + + if ($nextToken->isGivenKind([\T_IF, \T_TRY, \T_DO])) { + $openingTokenKind = $nextToken->getId(); + + while (true) { + $nextIndex = $tokens->getNextMeaningfulToken($endIndex); + \assert(isset(self::CONTROL_CONTINUATION_TOKENS[$openingTokenKind])); + if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(self::CONTROL_CONTINUATION_TOKENS[$openingTokenKind])) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); + + $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + + \assert(isset(self::FINAL_CONTROL_CONTINUATION_TOKENS[$openingTokenKind])); + if ($tokens[$nextIndex]->isGivenKind(self::FINAL_CONTROL_CONTINUATION_TOKENS[$openingTokenKind])) { + return $endIndex; + } + } else { + break; + } + } + } + + return $endIndex; + } + + $index = $parenthesisEndIndex; + + while (true) { + $token = $tokens[++$index]; + + // if there is some block in statement (eg lambda function) we need to skip it + if ($token->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($token->equals(';')) { + return $index; + } + + if ($token->isGivenKind(\T_CLOSE_TAG)) { + return $tokens->getPrevNonWhitespace($index); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php new file mode 100644 index 0000000..937a4e6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php @@ -0,0 +1,163 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * position?: 'next_line'|'same_line', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * position: 'next_line'|'same_line', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ControlStructureContinuationPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const NEXT_LINE = 'next_line'; + + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + + private const CONTROL_CONTINUATION_TOKENS = [ + \T_CATCH, + \T_ELSE, + \T_ELSEIF, + \T_FINALLY, + \T_WHILE, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Control structure continuation keyword must be on the configured line.', + [ + new CodeSample( + <<<'PHP' + self::NEXT_LINE], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::CONTROL_CONTINUATION_TOKENS); + } + + /** + * {@inheritdoc} + * + * Must run after ControlStructureBracesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('position', 'The position of the keyword that continues the control structure.')) + ->setAllowedValues([self::NEXT_LINE, self::SAME_LINE]) + ->setDefault(self::SAME_LINE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixControlContinuationBraces($tokens); + } + + private function fixControlContinuationBraces(Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 < $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(self::CONTROL_CONTINUATION_TOKENS)) { + continue; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + $prevToken = $tokens[$prevIndex]; + + if (!$prevToken->equals('}')) { + continue; + } + + if ($token->isGivenKind(\T_WHILE)) { + $prevIndex = $tokens->getPrevMeaningfulToken( + $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $prevIndex), + ); + + if (!$tokens[$prevIndex]->isGivenKind(\T_DO)) { + continue; + } + } + + $tokens->ensureWhitespaceAtIndex( + $index - 1, + 1, + self::NEXT_LINE === $this->configuration['position'] + ? $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $index) + : ' ', + ); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php new file mode 100644 index 0000000..7ed9f4a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.1. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ElseifFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words.', + [new CodeSample("isAllTokenKindsFound([\T_IF, \T_ELSE]); + } + + /** + * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF). + * + * {@inheritdoc} + */ + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_ELSE)) { + continue; + } + + $ifTokenIndex = $tokens->getNextMeaningfulToken($index); + + // if next meaningful token is not T_IF - continue searching, this is not the case for fixing + if (!$tokens[$ifTokenIndex]->isGivenKind(\T_IF)) { + continue; + } + + // if next meaningful token is T_IF, but uses an alternative syntax - this is not the case for fixing neither + $conditionEndBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $tokens->getNextMeaningfulToken($ifTokenIndex)); + $afterConditionIndex = $tokens->getNextMeaningfulToken($conditionEndBraceIndex); + if ($tokens[$afterConditionIndex]->equals(':')) { + continue; + } + + // now we have T_ELSE following by T_IF with no alternative syntax so we could fix this + // 1. clear whitespaces between T_ELSE and T_IF + $tokens->clearAt($index + 1); + + // 2. change token from T_ELSE into T_ELSEIF + $tokens[$index] = new Token([\T_ELSEIF, 'elseif']); + + // 3. clear succeeding T_IF + $tokens->clearAt($ifTokenIndex); + + $beforeIfTokenIndex = $tokens->getPrevNonWhitespace($ifTokenIndex); + + // 4. clear extra whitespace after T_IF in T_COMMENT,T_WHITESPACE?,T_IF,T_WHITESPACE sequence + if ($tokens[$beforeIfTokenIndex]->isComment() && $tokens[$ifTokenIndex + 1]->isWhitespace()) { + $tokens->clearAt($ifTokenIndex + 1); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php new file mode 100644 index 0000000..2261558 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * style?: 'braces'|'semicolon', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * style: 'braces'|'semicolon', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EmptyLoopBodyFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const STYLE_BRACES = 'braces'; + + private const STYLE_SEMICOLON = 'semicolon'; + + private const TOKEN_LOOP_KINDS = [\T_FOR, \T_FOREACH, \T_WHILE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty loop-body must be in configured style.', + [ + new CodeSample(" self::STYLE_BRACES, + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + * Must run after NoEmptyStatementFixer. + */ + public function getPriority(): int + { + return 39; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::STYLE_BRACES === $this->configuration['style']) { + $analyzer = new TokensAnalyzer($tokens); + $fixLoop = static function (int $index, int $endIndex) use ($tokens, $analyzer): void { + if ($tokens[$index]->isGivenKind(\T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { + return; + } + + $semiColonIndex = $tokens->getNextMeaningfulToken($endIndex); + + if (!$tokens[$semiColonIndex]->equals(';')) { + return; + } + + $tokens[$semiColonIndex] = new Token('{'); + $tokens->insertAt($semiColonIndex + 1, new Token('}')); + }; + } else { + $fixLoop = static function (int $index, int $endIndex) use ($tokens): void { + $braceOpenIndex = $tokens->getNextMeaningfulToken($endIndex); + + if (!$tokens[$braceOpenIndex]->equals('{')) { + return; + } + + $braceCloseIndex = $tokens->getNextNonWhitespace($braceOpenIndex); + + if (!$tokens[$braceCloseIndex]->equals('}')) { + return; + } + + $tokens[$braceOpenIndex] = new Token(';'); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex); + }; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(self::TOKEN_LOOP_KINDS)) { + $endIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $endIndex); // proceed to close ')' + $fixLoop($index, $endIndex); // fix loop if needs fixing + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Style of empty loop-bodies.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([self::STYLE_BRACES, self::STYLE_SEMICOLON]) + ->setDefault(self::STYLE_SEMICOLON) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php new file mode 100644 index 0000000..a303aec --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * style?: 'for'|'while', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * style: 'for'|'while', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EmptyLoopConditionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const STYLE_FOR = 'for'; + + private const STYLE_WHILE = 'while'; + + private const TOKEN_LOOP_KINDS = [\T_FOR, \T_WHILE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Empty loop-condition must be in configured style.', + [ + new CodeSample(" self::STYLE_FOR]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::STYLE_WHILE === $this->configuration['style']) { + $candidateLoopKinds = [\T_FOR, \T_WHILE]; + $replacement = [new Token([\T_WHILE, 'while']), new Token([\T_WHITESPACE, ' ']), new Token('('), new Token([\T_STRING, 'true']), new Token(')')]; + + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { + if (self::isForLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } elseif (self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + $doIndex = self::getDoIndex($tokens, $index); + + if (null !== $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + } + }; + } else { // self::STYLE_FOR + $candidateLoopKinds = [\T_WHILE]; + $replacement = [new Token([\T_FOR, 'for']), new Token('('), new Token(';'), new Token(';'), new Token(')')]; + + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { + if (!self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + return; + } + + $doIndex = self::getDoIndex($tokens, $index); + + if (null === $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } else { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + }; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($candidateLoopKinds)) { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); // proceed to close ')' + $fixLoop($index, $openIndex, $endIndex); // fix loop if needed + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Style of empty loop-condition.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([self::STYLE_WHILE, self::STYLE_FOR]) + ->setDefault(self::STYLE_WHILE) + ->getOption(), + ]); + } + + private static function clearNotCommentsInRange(Tokens $tokens, int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + + /** + * @param list $replacement + */ + private static function cloneAndInsert(Tokens $tokens, int $index, array $replacement): void + { + $replacementClones = []; + + foreach ($replacement as $token) { + $replacementClones[] = clone $token; + } + + $tokens->insertAt($index, $replacementClones); + } + + private static function getDoIndex(Tokens $tokens, int $index): ?int + { + $endIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$endIndex]->equals('}')) { + return null; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $endIndex); + $index = $tokens->getPrevMeaningfulToken($startIndex); + + return null === $index || !$tokens[$index]->isGivenKind(\T_DO) ? null : $index; + } + + private static function isForLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool + { + if (!$tokens[$index]->isGivenKind(\T_FOR)) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($openIndex); + + if (null === $index || !$tokens[$index]->equals(';')) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + + return null !== $index && $tokens[$index]->equals(';') && $endIndex === $tokens->getNextMeaningfulToken($index); + } + + private static function isWhileLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool + { + if (!$tokens[$index]->isGivenKind(\T_WHILE)) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($openIndex); + + return null !== $index && $tokens[$index]->equals([\T_STRING, 'true']) && $endIndex === $tokens->getNextMeaningfulToken($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php new file mode 100644 index 0000000..c3a762d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class IncludeFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Include/Require and file path should be divided with a single space. File path should not be placed within parentheses.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->clearIncludies($tokens, $this->findIncludies($tokens)); + } + + /** + * @param array $includies + */ + private function clearIncludies(Tokens $tokens, array $includies): void + { + $blocksAnalyzer = new BlocksAnalyzer(); + + foreach ($includies as $includy) { + if (!$tokens[$includy['end']]->isGivenKind(\T_CLOSE_TAG)) { + $afterEndIndex = $tokens->getNextNonWhitespace($includy['end']); + + if (null === $afterEndIndex || !$tokens[$afterEndIndex]->isComment()) { + $tokens->removeLeadingWhitespace($includy['end']); + } + } + + $braces = $includy['braces']; + + if (null !== $braces) { + $prevIndex = $tokens->getPrevMeaningfulToken($includy['begin']); + $nextIndex = $tokens->getNextMeaningfulToken($braces['close']); + + // Include is also legal as function parameter or condition statement but requires being wrapped then. + if (!$tokens[$nextIndex]->equalsAny([';', [\T_CLOSE_TAG]]) && !$blocksAnalyzer->isBlock($tokens, $prevIndex, $nextIndex)) { + continue; + } + + $this->removeWhitespaceAroundIfPossible($tokens, $braces['open']); + $this->removeWhitespaceAroundIfPossible($tokens, $braces['close']); + $tokens->clearTokenAndMergeSurroundingWhitespace($braces['open']); + $tokens->clearTokenAndMergeSurroundingWhitespace($braces['close']); + } + + $nextIndex = $tokens->getNonEmptySibling($includy['begin'], 1); + + if ($tokens[$nextIndex]->isWhitespace()) { + $tokens[$nextIndex] = new Token([\T_WHITESPACE, ' ']); + } elseif (null !== $braces || $tokens[$nextIndex]->isGivenKind([\T_VARIABLE, \T_CONSTANT_ENCAPSED_STRING, \T_COMMENT])) { + $tokens->insertAt($includy['begin'] + 1, new Token([\T_WHITESPACE, ' '])); + } + } + } + + /** + * @return array + */ + private function findIncludies(Tokens $tokens): array + { + $includies = []; + + foreach ($tokens->findGivenKind([\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]) as $includyTokens) { + foreach ($includyTokens as $index => $token) { + $includy = [ + 'begin' => $index, + 'braces' => null, + 'end' => $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]), + ]; + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$braceOpenIndex]->equals('(')) { + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $braceOpenIndex); + + $includy['braces'] = [ + 'open' => $braceOpenIndex, + 'close' => $braceCloseIndex, + ]; + } + + $includies[$index] = $includy; + } + } + + krsort($includies); + + return $includies; + } + + private function removeWhitespaceAroundIfPossible(Tokens $tokens, int $index): void + { + $nextIndex = $tokens->getNextNonWhitespace($index); + + if (null === $nextIndex || !$tokens[$nextIndex]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if (null === $prevIndex || !$tokens[$prevIndex]->isComment()) { + $tokens->removeTrailingWhitespace($index); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php new file mode 100644 index 0000000..42f5a7c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php @@ -0,0 +1,247 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * fix_non_monolithic_code?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * fix_non_monolithic_code: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Eddilbert Macharia + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoAlternativeSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace control structure alternative syntax to use braces.', + [ + new CodeSample( + "\nLorem ipsum.\n\n", + ['fix_non_monolithic_code' => true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->hasAlternativeSyntax() && (true === $this->configuration['fix_non_monolithic_code'] || $tokens->isMonolithicPhp()); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ElseifFixer, NoSuperfluousElseifFixer, NoUnneededControlParenthesesFixer, NoUselessElseFixer, SwitchContinueToBreakFixer. + */ + public function getPriority(): int + { + return 42; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_non_monolithic_code', 'Whether to also fix code with inline HTML.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(false, true)) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + $this->fixElseif($index, $token, $tokens); + $this->fixElse($index, $token, $tokens); + $this->fixOpenCloseControls($index, $token, $tokens); + } + } + + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + + return $nextToken->equals('(') + ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex) + : $structureTokenIndex; // return if next token is not opening parenthesis + } + + /** + * Handle both extremes of the control structures. + * e.g. if(): or endif;. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixOpenCloseControls(int $index, Token $token, Tokens $tokens): void + { + if ($token->isGivenKind([\T_IF, \T_FOREACH, \T_WHILE, \T_FOR, \T_SWITCH, \T_DECLARE])) { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + $afterParenthesisIndex = $tokens->getNextMeaningfulToken($closeIndex); + $afterParenthesis = $tokens[$afterParenthesisIndex]; + + if (!$afterParenthesis->equals(':')) { + return; + } + + $items = []; + + if (!$tokens[$afterParenthesisIndex - 1]->isWhitespace()) { + $items[] = new Token([\T_WHITESPACE, ' ']); + } + + $items[] = new Token('{'); + + if (!$tokens[$afterParenthesisIndex + 1]->isWhitespace()) { + $items[] = new Token([\T_WHITESPACE, ' ']); + } + + $tokens->clearAt($afterParenthesisIndex); + $tokens->insertAt($afterParenthesisIndex, $items); + } + + if (!$token->isGivenKind([\T_ENDIF, \T_ENDFOREACH, \T_ENDWHILE, \T_ENDFOR, \T_ENDSWITCH, \T_ENDDECLARE])) { + return; + } + + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextTokenIndex]; + $tokens[$index] = new Token('}'); + + if ($nextToken->equals(';')) { + $tokens->clearAt($nextTokenIndex); + } + } + + /** + * Handle the else: cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElse(int $index, Token $token, Tokens $tokens): void + { + if (!$token->isGivenKind(\T_ELSE)) { + return; + } + + $tokenAfterElseIndex = $tokens->getNextMeaningfulToken($index); + $tokenAfterElse = $tokens[$tokenAfterElseIndex]; + + if (!$tokenAfterElse->equals(':')) { + return; + } + + $this->addBraces($tokens, new Token([\T_ELSE, 'else']), $index, $tokenAfterElseIndex); + } + + /** + * Handle the elsif(): cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElseif(int $index, Token $token, Tokens $tokens): void + { + if (!$token->isGivenKind(\T_ELSEIF)) { + return; + } + + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $tokenAfterParenthesisIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + $tokenAfterParenthesis = $tokens[$tokenAfterParenthesisIndex]; + + if (!$tokenAfterParenthesis->equals(':')) { + return; + } + + $this->addBraces($tokens, new Token([\T_ELSEIF, 'elseif']), $index, $tokenAfterParenthesisIndex); + } + + /** + * Add opening and closing braces to the else: and elseif: cases. + * + * @param Tokens $tokens the tokens collection + * @param Token $token the current token + * @param int $index the current token index + * @param int $colonIndex the index of the colon + */ + private function addBraces(Tokens $tokens, Token $token, int $index, int $colonIndex): void + { + $items = [ + new Token('}'), + new Token([\T_WHITESPACE, ' ']), + $token, + ]; + + if (!$tokens[$index + 1]->isWhitespace()) { + $items[] = new Token([\T_WHITESPACE, ' ']); + } + + $tokens->clearAt($index); + $tokens->insertAt( + $index, + $items, + ); + + // increment the position of the colon by number of items inserted + $colonIndex += \count($items); + + $items = [new Token('{')]; + + if (!$tokens[$colonIndex + 1]->isWhitespace()) { + $items[] = new Token([\T_WHITESPACE, ' ']); + } + + $tokens->clearAt($colonIndex); + $tokens->insertAt( + $colonIndex, + $items, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php new file mode 100644 index 0000000..8415cdf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php @@ -0,0 +1,369 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * Fixer for rule defined in PSR2 ¶5.2. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * comment_text?: string, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * comment_text: string, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoBreakCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const STRUCTURE_KINDS = [\T_FOR, \T_FOREACH, \T_WHILE, \T_IF, \T_ELSEIF, \T_SWITCH, \T_FUNCTION, FCT::T_MATCH]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be a comment when fall-through is intentional in a non-empty case body.', + [ + new CodeSample( + <<<'PHP' + 'some comment'], + ), + ], + 'Adds a "no break" comment before fall-through cases, and removes it if there is no fall-through.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_SWITCH); + } + + /** + * {@inheritdoc} + * + * Must run after NoUselessElseFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_text', 'The text to use in the added comment and to detect it.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([ + static function (string $value): bool { + if (Preg::match('/\R/', $value)) { + throw new InvalidOptionsException('The comment text must not contain new lines.'); + } + + return true; + }, + ]) + ->setNormalizer(static fn (Options $options, string $value): string => rtrim($value)) + ->setDefault('no break') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = \count($tokens) - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_DEFAULT)) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_ARROW)) { + continue; // this is "default" from "match" + } + } elseif ( + !$tokens[$index]->isGivenKind(\T_CASE) + || $analyzer->isEnumCase($index) + ) { + continue; + } + + $this->fixCase($tokens, $tokens->getNextTokenOfKind($index, [':', ';'])); + } + } + + private function fixCase(Tokens $tokens, int $casePosition): void + { + $empty = true; + $fallThrough = true; + $commentPosition = null; + + for ($i = $casePosition + 1, $max = \count($tokens); $i < $max; ++$i) { + if ($tokens[$i]->isGivenKind([...self::STRUCTURE_KINDS, \T_ELSE, \T_DO, \T_CLASS])) { + $empty = false; + $i = $this->getStructureEnd($tokens, $i); + + continue; + } + + if ($tokens[$i]->isGivenKind([\T_BREAK, \T_CONTINUE, \T_RETURN, \T_EXIT, \T_GOTO])) { + $fallThrough = false; + + continue; + } + + if ($tokens[$i]->isGivenKind(\T_THROW)) { + $previousIndex = $tokens->getPrevMeaningfulToken($i); + + if ($previousIndex === $casePosition || $tokens[$previousIndex]->equalsAny(['{', ';', '}', [\T_OPEN_TAG]])) { + $fallThrough = false; + } + + continue; + } + + if ($tokens[$i]->equals('}') || $tokens[$i]->isGivenKind(\T_ENDSWITCH)) { + if (null !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + } + + break; + } + + if ($this->isNoBreakComment($tokens[$i])) { + $commentPosition = $i; + + continue; + } + + if ($tokens[$i]->isGivenKind([\T_CASE, \T_DEFAULT])) { + if (!$empty && $fallThrough) { + if (null !== $commentPosition && $tokens->getPrevNonWhitespace($i) !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + $commentPosition = null; + } + + if (null === $commentPosition) { + $this->insertCommentAt($tokens, $i); + } else { + $text = $this->configuration['comment_text']; + $tokens[$commentPosition] = new Token([ + $tokens[$commentPosition]->getId(), + str_ireplace($text, $text, $tokens[$commentPosition]->getContent()), + ]); + + $this->ensureNewLineAt($tokens, $commentPosition); + } + } elseif (null !== $commentPosition) { + $this->removeComment($tokens, $commentPosition); + } + + break; + } + + if (!$tokens[$i]->isGivenKind([\T_COMMENT, \T_WHITESPACE])) { + $empty = false; + } + } + } + + private function isNoBreakComment(Token $token): bool + { + if (!$token->isComment()) { + return false; + } + + $text = preg_quote($this->configuration['comment_text'], '~'); + + return Preg::match("~^((//|#)\\s*{$text}\\s*)|(/\\*\\*?\\s*{$text}(\\s+.*)*\\*/)$~i", $token->getContent()); + } + + private function insertCommentAt(Tokens $tokens, int $casePosition): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $newlinePosition = $this->ensureNewLineAt($tokens, $casePosition); + $newlineToken = $tokens[$newlinePosition]; + $nbNewlines = substr_count($newlineToken->getContent(), $lineEnding); + + if ($newlineToken->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $newlineToken->getContent())) { + ++$nbNewlines; + } elseif ($tokens[$newlinePosition - 1]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $tokens[$newlinePosition - 1]->getContent())) { + ++$nbNewlines; + + if (!Preg::match('/\R/', $newlineToken->getContent())) { + $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $lineEnding.$newlineToken->getContent()]); + } + } + + if ($nbNewlines > 1) { + Preg::match('/^(.*?)(\R\h*)$/s', $newlineToken->getContent(), $matches); + \assert(isset($matches[1], $matches[2])); + + $indent = WhitespacesAnalyzer::detectIndent($tokens, $newlinePosition - 1); + $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $matches[1].$lineEnding.$indent]); + $tokens->insertAt(++$newlinePosition, new Token([\T_WHITESPACE, $matches[2]])); + } + + $tokens->insertAt($newlinePosition, new Token([\T_COMMENT, '// '.$this->configuration['comment_text']])); + $this->ensureNewLineAt($tokens, $newlinePosition); + } + + /** + * @return int The newline token position + */ + private function ensureNewLineAt(Tokens $tokens, int $position): int + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $content = $lineEnding.WhitespacesAnalyzer::detectIndent($tokens, $position); + $whitespaceToken = $tokens[$position - 1]; + + if (!$whitespaceToken->isGivenKind(\T_WHITESPACE)) { + if ($whitespaceToken->isGivenKind(\T_OPEN_TAG)) { + $content = Preg::replace('/\R/', '', $content); + + if (!Preg::match('/\R/', $whitespaceToken->getContent())) { + $tokens[$position - 1] = new Token([\T_OPEN_TAG, Preg::replace('/\s+$/', $lineEnding, $whitespaceToken->getContent())]); + } + } + + if ('' !== $content) { + $tokens->insertAt($position, new Token([\T_WHITESPACE, $content])); + + return $position; + } + + return $position - 1; + } + + if ($tokens[$position - 2]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $tokens[$position - 2]->getContent())) { + $content = Preg::replace('/^\R/', '', $content); + } + + if (!Preg::match('/\R/', $whitespaceToken->getContent())) { + $tokens[$position - 1] = new Token([\T_WHITESPACE, $content]); + } + + return $position - 1; + } + + private function removeComment(Tokens $tokens, int $commentPosition): void + { + if ($tokens[$tokens->getPrevNonWhitespace($commentPosition)]->isGivenKind(\T_OPEN_TAG)) { + $whitespacePosition = $commentPosition + 1; + $regex = '/^\R\h*/'; + } else { + $whitespacePosition = $commentPosition - 1; + $regex = '/\R\h*$/'; + } + + $whitespaceToken = $tokens[$whitespacePosition]; + + if ($whitespaceToken->isGivenKind(\T_WHITESPACE)) { + $content = Preg::replace($regex, '', $whitespaceToken->getContent()); + + $tokens->ensureWhitespaceAtIndex($whitespacePosition, 0, $content); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($commentPosition); + } + + private function getStructureEnd(Tokens $tokens, int $position): int + { + $initialToken = $tokens[$position]; + + if ($initialToken->isGivenKind(self::STRUCTURE_KINDS)) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS, + $tokens->getNextTokenOfKind($position, ['(']), + ); + } elseif ($initialToken->isGivenKind(\T_CLASS)) { + $openParenthesisPosition = $tokens->getNextMeaningfulToken($position); + + if ('(' === $tokens[$openParenthesisPosition]->getContent()) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS, + $openParenthesisPosition, + ); + } + } + + if ($initialToken->isGivenKind(\T_FUNCTION)) { + $position = $tokens->getNextTokenOfKind($position, ['{']); + } else { + $position = $tokens->getNextMeaningfulToken($position); + } + + if ('{' !== $tokens[$position]->getContent()) { + return $tokens->getNextTokenOfKind($position, [';']); + } + + $position = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $position); + + if ($initialToken->isGivenKind(\T_DO)) { + $position = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS, + $tokens->getNextTokenOfKind($position, ['(']), + ); + + return $tokens->getNextTokenOfKind($position, [';']); + } + + return $position; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php new file mode 100644 index 0000000..9af1041 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSuperfluousElseifFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ELSE, \T_ELSEIF]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces superfluous `elseif` with `if`.', + [ + new CodeSample(" $token) { + if ($this->isElseif($tokens, $index) && $this->isSuperfluousElse($tokens, $index)) { + $this->convertElseifToIf($tokens, $index); + } + } + } + + private function isElseif(Tokens $tokens, int $index): bool + { + return + $tokens[$index]->isGivenKind(\T_ELSEIF) + || ($tokens[$index]->isGivenKind(\T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF)); + } + + private function convertElseifToIf(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isGivenKind(\T_ELSE)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens[$index] = new Token([\T_IF, 'if']); + } + + $whitespace = ''; + + for ($previous = $index - 1; $previous > 0; --$previous) { + $token = $tokens[$previous]; + if ($token->isWhitespace() && Preg::match('/(\R\N*)$/', $token->getContent(), $matches)) { + $whitespace = $matches[1]; + + break; + } + } + + if ('' === $whitespace) { + return; + } + + $previousToken = $tokens[$index - 1]; + + if (!$previousToken->isWhitespace()) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, $whitespace])); + } elseif (!Preg::match('/\R/', $previousToken->getContent())) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, $whitespace]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php new file mode 100644 index 0000000..570a0f2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingCommaInListCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove trailing commas in list function calls.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array_destructuring']]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php new file mode 100644 index 0000000..7ccb9e4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededBracesFixer.php @@ -0,0 +1,202 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * namespaces?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * namespaces: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnneededBracesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes unneeded braces that are superfluous and aren\'t part of a control structure\'s body.', + [ + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return 40; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['}', CT::T_GROUP_IMPORT_BRACE_CLOSE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($this->findBraceOpen($tokens) as $index) { + if ($this->isOverComplete($tokens, $index)) { + $this->clearOverCompleteBraces($tokens, $index); + } + } + + if (true === $this->configuration['namespaces']) { + $this->clearIfIsOverCompleteNamespaceBlock($tokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('namespaces', 'Remove unneeded braces from bracketed namespaces.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param int $openIndex index of `{` token + */ + private function clearOverCompleteBraces(Tokens $tokens, int $openIndex): void + { + $blockType = Tokens::detectBlockType($tokens[$openIndex]); + + $closeIndex = $tokens->findBlockEnd($blockType['type'], $openIndex); + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + } + + /** + * @return iterable + */ + private function findBraceOpen(Tokens $tokens): iterable + { + for ($i = \count($tokens) - 1; $i > 0; --$i) { + if ($tokens[$i]->equalsAny(['{', [CT::T_GROUP_IMPORT_BRACE_OPEN]])) { + yield $i; + } + } + } + + /** + * @param int $index index of `{` token + */ + private function isOverComplete(Tokens $tokens, int $index): bool + { + if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $commaOrCloseBraceIndex = $tokens->getNextTokenOfKind($index, [',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]]); + + $analyzer = new TokensAnalyzer($tokens); + if ($analyzer->isBlockMultiline($tokens, $index)) { + return false; + } + + return $tokens[$commaOrCloseBraceIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE); + } + + return $tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['{', '}', [\T_OPEN_TAG], ':', ';']); + } + + private function clearIfIsOverCompleteNamespaceBlock(Tokens $tokens): void + { + if (1 !== $tokens->countTokenKind(\T_NAMESPACE)) { + return; // fast check, we never fix if multiple namespaces are defined + } + + $index = $tokens->getNextTokenOfKind(0, [[\T_NAMESPACE]]); + + $namespaceIsNamed = false; + + $index = $tokens->getNextMeaningfulToken($index); + while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + $index = $tokens->getNextMeaningfulToken($index); + $namespaceIsNamed = true; + } + + if (!$namespaceIsNamed) { + return; + } + + if (!$tokens[$index]->equals('{')) { + return; // `;` + } + + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + if (null !== $afterCloseIndex && (!$tokens[$afterCloseIndex]->isGivenKind(\T_CLOSE_TAG) || null !== $tokens->getNextMeaningfulToken($afterCloseIndex))) { + return; + } + + // clear up + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens[$index] = new Token(';'); + + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index - 1); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php new file mode 100644 index 0000000..c4cfdb8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php @@ -0,0 +1,743 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * statements?: list<'break'|'clone'|'continue'|'echo_print'|'negative_instanceof'|'others'|'return'|'switch_case'|'yield'|'yield_from'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * statements: list<'break'|'clone'|'continue'|'echo_print'|'negative_instanceof'|'others'|'return'|'switch_case'|'yield'|'yield_from'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @author Sullivan Senechal + * @author Dariusz Rumiński + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var non-empty-list + */ + private const BLOCK_TYPES = [ + Tokens::BLOCK_TYPE_INDEX_BRACE, + Tokens::BLOCK_TYPE_ARRAY_BRACKET, + Tokens::BLOCK_TYPE_BRACE, + Tokens::BLOCK_TYPE_DESTRUCTURING_BRACKET, + Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, + Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, + Tokens::BLOCK_TYPE_INDEX_BRACKET, + Tokens::BLOCK_TYPE_PARENTHESIS, + ]; + + private const BEFORE_TYPES = [ + ';', + '{', + [\T_OPEN_TAG], + [\T_OPEN_TAG_WITH_ECHO], + [\T_ECHO], + [\T_PRINT], + [\T_RETURN], + [\T_THROW], + [\T_YIELD], + [\T_YIELD_FROM], + [\T_BREAK], + [\T_CONTINUE], + // won't be fixed, but true in concept, helpful for fast check + [\T_REQUIRE], + [\T_REQUIRE_ONCE], + [\T_INCLUDE], + [\T_INCLUDE_ONCE], + ]; + + private const CONFIG_OPTIONS = [ + 'break', + 'clone', + 'continue', + 'echo_print', + 'negative_instanceof', + 'others', + 'return', + 'switch_case', + 'yield', + 'yield_from', + ]; + + private const TOKEN_TYPE_CONFIG_MAP = [ + \T_BREAK => 'break', + \T_CASE => 'switch_case', + \T_CONTINUE => 'continue', + \T_ECHO => 'echo_print', + \T_PRINT => 'echo_print', + \T_RETURN => 'return', + \T_YIELD => 'yield', + \T_YIELD_FROM => 'yield_from', + ]; + + // handled by the `include` rule + private const TOKEN_TYPE_NO_CONFIG = [ + \T_REQUIRE, + \T_REQUIRE_ONCE, + \T_INCLUDE, + \T_INCLUDE_ONCE, + ]; + private const KNOWN_NEGATIVE_PRE_TYPES = [ + [CT::T_CLASS_CONSTANT], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_RETURN_REF], + [CT::T_USE_LAMBDA], + [\T_ARRAY], + [\T_CATCH], + [\T_CLASS], + [\T_DECLARE], + [\T_ELSEIF], + [\T_EMPTY], + [\T_EXIT], + [\T_EVAL], + [\T_FN], + [\T_FOREACH], + [\T_FOR], + [\T_FUNCTION], + [\T_HALT_COMPILER], + [\T_IF], + [\T_ISSET], + [\T_LIST], + [\T_STRING], + [\T_SWITCH], + [\T_STATIC], + [\T_UNSET], + [\T_VARIABLE], + [\T_WHILE], + // handled by the `include` rule + [\T_REQUIRE], + [\T_REQUIRE_ONCE], + [\T_INCLUDE], + [\T_INCLUDE_ONCE], + [FCT::T_MATCH], + ]; + + /** + * @var list<_PhpTokenPrototypePartial> + */ + private array $noopTypes; + + private TokensAnalyzer $tokensAnalyzer; + + public function __construct() + { + parent::__construct(); + + $this->noopTypes = [ + '$', + [\T_CONSTANT_ENCAPSED_STRING], + [\T_DNUMBER], + [\T_DOUBLE_COLON], + [\T_LNUMBER], + [\T_NS_SEPARATOR], + [\T_STRING], + [\T_VARIABLE], + [\T_STATIC], + // magic constants + [\T_CLASS_C], + [\T_DIR], + [\T_FILE], + [\T_FUNC_C], + [\T_LINE], + [\T_METHOD_C], + [\T_NS_C], + [\T_TRAIT_C], + ]; + + foreach (Token::getObjectOperatorKinds() as $kind) { + $this->noopTypes[] = [$kind]; + } + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes unneeded parentheses around control statements.', + [ + new CodeSample( + <<<'PHP' + ['break', 'continue']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before ConcatSpaceFixer, NewExpressionParenthesesFixer, NoTrailingWhitespaceFixer. + * Must run after ModernizeTypesCastingFixer, NoAlternativeSyntaxFixer. + */ + public function getPriority(): int + { + return 30; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['(', CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokens as $openIndex => $token) { + if ($token->equals('(')) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + } elseif ($token->isGivenKind(CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN)) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CLASS_INSTANTIATION_PARENTHESIS, $openIndex); + } else { + continue; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($openIndex); + $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + // do a cheap check for negative case: `X()` + + if ($tokens->getNextMeaningfulToken($openIndex) === $closeIndex) { + if ($tokens[$beforeOpenIndex]->isGivenKind(\T_EXIT)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'others'); + } + + continue; + } + + // do a cheap check for negative case: `foo(1,2)` + + if ($tokens[$beforeOpenIndex]->equalsAny(self::KNOWN_NEGATIVE_PRE_TYPES)) { + continue; + } + + // check for the simple useless wrapped cases + + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + + continue; + } + + // handle `clone` statements + + if ($tokens[$beforeOpenIndex]->isGivenKind(\T_CLONE)) { + if ($this->isWrappedCloneArgument($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'clone'); + } + + continue; + } + + // handle `instance of` statements + + $instanceOfIndex = $this->getIndexOfInstanceOfStatement($tokens, $openIndex, $closeIndex); + + if (null !== $instanceOfIndex) { + if ($this->isWrappedInstanceOf($tokens, $instanceOfIndex, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair( + $tokens, + $beforeOpenIndex, + $afterCloseIndex, + $openIndex, + $closeIndex, + $tokens[$beforeOpenIndex]->equals('!') ? 'negative_instanceof' : 'others', + ); + } + + continue; + } + + // last checks deal with operators, do not swap around + + if ($this->isWrappedPartOfOperation($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $defaults = array_filter( + self::CONFIG_OPTIONS, + static fn (string $option): bool => 'negative_instanceof' !== $option && 'others' !== $option && 'yield_from' !== $option, + ); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('statements', 'List of control statements to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(self::CONFIG_OPTIONS)]) + ->setDefault(array_values($defaults)) + ->getOption(), + ]); + } + + private function isUselessWrapped(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + return + $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedLanguageConstructArgument($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + private function isWrappedCloneArgument(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ( + !( + $tokens[$beforeOpenIndex]->equals('?') // For BC reasons + || $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex) + ) + ) { + return false; + } + + $newCandidateIndex = $tokens->getNextMeaningfulToken($openIndex); + + if ($tokens[$newCandidateIndex]->isGivenKind(\T_NEW)) { + $openIndex = $newCandidateIndex; // `clone (new X)`, `clone (new X())`, clone (new X(Y))` + } + + return !$this->containsOperation($tokens, $openIndex, $closeIndex); + } + + private function getIndexOfInstanceOfStatement(Tokens $tokens, int $openIndex, int $closeIndex): ?int + { + $instanceOfIndex = $tokens->findGivenKind(\T_INSTANCEOF, $openIndex, $closeIndex); + + return 1 === \count($instanceOfIndex) ? array_key_first($instanceOfIndex) : null; + } + + private function isWrappedInstanceOf(Tokens $tokens, int $instanceOfIndex, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + if ( + $this->containsOperation($tokens, $openIndex, $instanceOfIndex) + || $this->containsOperation($tokens, $instanceOfIndex, $closeIndex) + ) { + return false; + } + + if ($tokens[$beforeOpenIndex]->equals('!')) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + return + $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) + || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + private function isWrappedPartOfOperation(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool + { + if ($this->containsOperation($tokens, $openIndex, $closeIndex)) { + return false; + } + + $boundariesMoved = false; + + if ($this->isPreUnaryOperation($tokens, $beforeOpenIndex)) { + $beforeOpenIndex = $this->getBeforePreUnaryOperation($tokens, $beforeOpenIndex); + $boundariesMoved = true; + } + + if ($this->isAccess($tokens, $afterCloseIndex)) { + $afterCloseIndex = $this->getAfterAccess($tokens, $afterCloseIndex); + $boundariesMoved = true; + + if ($this->tokensAnalyzer->isUnarySuccessorOperator($afterCloseIndex)) { // post unary operation are only valid here + $afterCloseIndex = $tokens->getNextMeaningfulToken($afterCloseIndex); + } + } + + if ($boundariesMoved) { + if ($tokens[$beforeOpenIndex]->equalsAny(self::KNOWN_NEGATIVE_PRE_TYPES)) { + return false; + } + + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + return true; + } + } + + // check if part of some operation sequence + + $beforeIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($beforeOpenIndex); + $afterIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($afterCloseIndex); + + if ($beforeIsBinaryOperation && $afterIsBinaryOperation) { + return true; // `+ (x) +` + } + + $beforeToken = $tokens[$beforeOpenIndex]; + $afterToken = $tokens[$afterCloseIndex]; + + $beforeIsBlockOpenOrComma = $beforeToken->equals(',') || null !== $this->getBlock($tokens, $beforeOpenIndex, true); + $afterIsBlockEndOrComma = $afterToken->equals(',') || null !== $this->getBlock($tokens, $afterCloseIndex, false); + + if (($beforeIsBlockOpenOrComma && $afterIsBinaryOperation) || ($beforeIsBinaryOperation && $afterIsBlockEndOrComma)) { + // $beforeIsBlockOpenOrComma && $afterIsBlockEndOrComma is covered by `isWrappedSequenceElement` + // `[ (x) +` or `+ (X) ]` or `, (X) +` or `+ (X) ,` + + return true; + } + + if ($tokens[$beforeOpenIndex]->equals('}')) { + $beforeIsStatementOpen = !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } else { + $beforeIsStatementOpen = $beforeToken->equalsAny(self::BEFORE_TYPES) || $beforeToken->isGivenKind(\T_CASE); + } + + $afterIsStatementEnd = $afterToken->equalsAny([';', [\T_CLOSE_TAG]]); + + return + ($beforeIsStatementOpen && $afterIsBinaryOperation) // `isGivenKind([\T_PRINT, \T_YIELD, \T_YIELD_FROM, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE])) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + return $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + + // any of `isGivenKind(\T_CASE)) { + return $tokens[$afterCloseIndex]->equalsAny([':', ';']); // `switch case` + } + + if (!$tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + return false; + } + + if ($tokens[$beforeOpenIndex]->equals('}')) { + return !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } + + return $tokens[$beforeOpenIndex]->equalsAny(self::BEFORE_TYPES); + } + + private function isSimpleAssignment(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + return $tokens[$beforeOpenIndex]->equals('=') && $tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]]); // `= (X) ;` + } + + private function isWrappedSequenceElement(Tokens $tokens, int $startIndex, int $endIndex): bool + { + $startIsComma = $tokens[$startIndex]->equals(','); + $endIsComma = $tokens[$endIndex]->equals(','); + + if ($startIsComma && $endIsComma) { + return true; // `,(X),` + } + + $blockTypeStart = $this->getBlock($tokens, $startIndex, true); + $blockTypeEnd = $this->getBlock($tokens, $endIndex, false); + + return + ($startIsComma && null !== $blockTypeEnd) // `,(X)]` + || ($endIsComma && null !== $blockTypeStart) // `[(X),` + || (null !== $blockTypeEnd && null !== $blockTypeStart); // any type of `{(X)}`, `[(X)]` and `((X))` + } + + // any of `for( (X); ;(X)) ;` note that the middle element is covered as 'single statement' as it is `; (X) ;` + private function isWrappedForElement(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + $forCandidateIndex = null; + + if ($tokens[$beforeOpenIndex]->equals('(') && $tokens[$afterCloseIndex]->equals(';')) { + $forCandidateIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } elseif ($tokens[$afterCloseIndex]->equals(')') && $tokens[$beforeOpenIndex]->equals(';')) { + $forCandidateIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $afterCloseIndex); + $forCandidateIndex = $tokens->getPrevMeaningfulToken($forCandidateIndex); + } + + return null !== $forCandidateIndex && $tokens[$forCandidateIndex]->isGivenKind(\T_FOR); + } + + // `fn() => (X);` + private function isWrappedFnBody(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool + { + if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_DOUBLE_ARROW)) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ($tokens[$beforeOpenIndex]->isGivenKind(\T_STRING)) { + while (true) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if (!$tokens[$beforeOpenIndex]->isGivenKind([\T_STRING, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION])) { + break; + } + } + + if (!$tokens[$beforeOpenIndex]->isGivenKind(CT::T_TYPE_COLON)) { + return false; + } + + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + if (!$tokens[$beforeOpenIndex]->equals(')')) { + return false; + } + + $beforeOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $beforeOpenIndex); + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + + if ($tokens[$beforeOpenIndex]->isGivenKind(CT::T_RETURN_REF)) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + + if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_FN)) { + return false; + } + + return $tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]); + } + + private function isPreUnaryOperation(Tokens $tokens, int $index): bool + { + return $this->tokensAnalyzer->isUnaryPredecessorOperator($index) || $tokens[$index]->isCast(); + } + + private function getBeforePreUnaryOperation(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($this->isPreUnaryOperation($tokens, $index)); + + return $index; + } + + // array access `(X)[` or `(X){` or object access `(X)->` or `(X)?->` + private function isAccess(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + return $token->isObjectOperator() || $token->equals('[') || $token->isGivenKind(CT::T_ARRAY_INDEX_BRACE_OPEN); + } + + private function getAfterAccess(Tokens $tokens, int $index): int + { + while (true) { + $block = $this->getBlock($tokens, $index, true); + + if (null !== $block) { + $index = $tokens->findBlockEnd($block['type'], $index); + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + if ( + $tokens[$index]->isObjectOperator() + || $tokens[$index]->equalsAny(['$', [\T_PAAMAYIM_NEKUDOTAYIM], [\T_STRING], [\T_VARIABLE]]) + ) { + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + break; + } + + return $index; + } + + /** + * @return null|array{type: Tokens::BLOCK_TYPE_*, isStart: bool} + */ + private function getBlock(Tokens $tokens, int $index, bool $isStart): ?array + { + $block = Tokens::detectBlockType($tokens[$index]); + + return null !== $block && $isStart === $block['isStart'] && \in_array($block['type'], self::BLOCK_TYPES, true) ? $block : null; + } + + private function containsOperation(Tokens $tokens, int $startIndex, int $endIndex): bool + { + while (true) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + + if ($startIndex === $endIndex) { + break; + } + + $block = Tokens::detectBlockType($tokens[$startIndex]); + + if (null !== $block && $block['isStart']) { + $startIndex = $tokens->findBlockEnd($block['type'], $startIndex); + + continue; + } + + if (!$tokens[$startIndex]->equalsAny($this->noopTypes)) { + return true; + } + } + + return false; + } + + private function getConfigType(Tokens $tokens, int $beforeOpenIndex): ?string + { + if ($tokens[$beforeOpenIndex]->isGivenKind(self::TOKEN_TYPE_NO_CONFIG)) { + return null; + } + + foreach (self::TOKEN_TYPE_CONFIG_MAP as $type => $configItem) { + if ($tokens[$beforeOpenIndex]->isGivenKind($type)) { + return $configItem; + } + } + + return 'others'; + } + + private function removeUselessParenthesisPair( + Tokens $tokens, + int $beforeOpenIndex, + int $afterCloseIndex, + int $openIndex, + int $closeIndex, + ?string $configType + ): void { + $statements = $this->configuration['statements']; + + if (null === $configType || !\in_array($configType, $statements, true)) { + return; + } + + $needsSpaceAfter = !$this->isAccess($tokens, $afterCloseIndex) + && !$tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]) + && null === $this->getBlock($tokens, $afterCloseIndex, false) + && !($tokens[$afterCloseIndex]->equalsAny([':', ';']) && $tokens[$beforeOpenIndex]->isGivenKind(\T_CASE)); + + $needsSpaceBefore = !$this->isPreUnaryOperation($tokens, $beforeOpenIndex) + && !$tokens[$beforeOpenIndex]->equalsAny(['}', [\T_EXIT], [\T_OPEN_TAG]]) + && null === $this->getBlock($tokens, $beforeOpenIndex, true); + + $this->removeBrace($tokens, $closeIndex, $needsSpaceAfter); + $this->removeBrace($tokens, $openIndex, $needsSpaceBefore); + } + + private function removeBrace(Tokens $tokens, int $index, bool $needsSpace): void + { + if ($needsSpace) { + foreach ([-1, 1] as $direction) { + $siblingIndex = $tokens->getNonEmptySibling($index, $direction); + + if ($tokens[$siblingIndex]->isWhitespace() || $tokens[$siblingIndex]->isComment()) { + $needsSpace = false; + + break; + } + } + } + + if ($needsSpace) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + private function closeCurlyBelongsToDynamicElement(Tokens $tokens, int $beforeOpenIndex): bool + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $beforeOpenIndex); + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + return true; + } + + if ($tokens[$index]->equals(':')) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_CASE], '?']); + + return !$tokens[$index]->isGivenKind(\T_CASE); + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php new file mode 100644 index 0000000..17dcf5b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * namespaces?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * namespaces: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnneededCurlyBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private NoUnneededBracesFixer $noUnneededBracesFixer; + + public function __construct() + { + $this->noUnneededBracesFixer = new NoUnneededBracesFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->noUnneededBracesFixer->getDefinition(); + + return new FixerDefinition( + 'Removes unneeded curly braces that are superfluous and aren\'t part of a control structure\'s body.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return $this->noUnneededBracesFixer->getPriority(); + } + + public function getSuccessorsNames(): array + { + return [ + $this->noUnneededBracesFixer->getName(), + ]; + } + + /** + * @param _AutogeneratedInputConfiguration $configuration + */ + protected function configurePreNormalisation(array $configuration): void + { + $this->noUnneededBracesFixer->configure($configuration); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('namespaces', 'Remove unneeded curly braces from bracketed namespaces.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [ + $this->noUnneededBracesFixer, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php new file mode 100644 index 0000000..09d875c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessElseFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_ELSE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless `else` cases.', + [ + new CodeSample(" $token) { + if (!$token->isGivenKind(\T_ELSE)) { + continue; + } + + // `else if` vs. `else` and alternative syntax `else:` checks + if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny([':', [\T_IF]])) { + continue; + } + + // clean up `else` if it is an empty statement + $this->fixEmptyElse($tokens, $index); + if ($tokens->isEmptyAt($index)) { + continue; + } + + // Clean up `else` if possible. + // Ignore `else` blocks containing named function or classy declarations, because in PHP function/class + // declarations outside any conditional block are always evaluated first, even if the code before the declaration + // returns/throws/etc. So removing such `else` blocks would change the behaviour. + if ($this->isSuperfluousElse($tokens, $index) && !$this->containsNamedSymbolDeclaration($tokens, $index)) { + $this->clearElse($tokens, $index); + } + } + } + + /** + * Remove tokens part of an `else` statement if not empty (i.e. no meaningful tokens inside). + * + * @param int $index T_ELSE index + */ + private function fixEmptyElse(Tokens $tokens, int $index): void + { + $next = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$next]->equals('{')) { + $close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $next); + if (1 === $close - $next) { // '{}' + $this->clearElse($tokens, $index); + } elseif ($tokens->getNextMeaningfulToken($next) === $close) { // '{/**/}' + $this->clearElse($tokens, $index); + } + + return; + } + + // short `else` + $end = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + if ($next === $end) { + $this->clearElse($tokens, $index); + } + } + + /** + * @param int $index index of T_ELSE + */ + private function clearElse(Tokens $tokens, int $index): void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + // clear T_ELSE and the '{' '}' if there are any + $next = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$next]->equals('{')) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $next)); + $tokens->clearTokenAndMergeSurroundingWhitespace($next); + } + + /** + * @param int $index index of T_ELSE + */ + private function containsNamedSymbolDeclaration(Tokens $tokens, int $index): bool + { + $next = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$next]->equals('{')) { + // short `else` can't contain symbol declaration (`else class Foo {}` is invalid syntax) + return false; + } + + $tokensAnalyzer = new TokensAnalyzer($tokens); + $close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $next); + for ($i = $next + 1; $i < $close; ++$i) { + if ($tokens[$i]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($i)) { + return true; + } + + if ($tokens[$i]->isClassy() && !$tokensAnalyzer->isAnonymousClass($i)) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php new file mode 100644 index 0000000..57c28f2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php @@ -0,0 +1,149 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SimplifiedIfReturnFixer extends AbstractFixer +{ + /** + * @var list}> + */ + private array $sequences = [ + [ + 'isNegative' => false, + 'sequence' => [ + '{', [\T_RETURN], [\T_STRING, 'true'], ';', '}', + [\T_RETURN], [\T_STRING, 'false'], ';', + ], + ], + [ + 'isNegative' => true, + 'sequence' => [ + '{', [\T_RETURN], [\T_STRING, 'false'], ';', '}', + [\T_RETURN], [\T_STRING, 'true'], ';', + ], + ], + [ + 'isNegative' => false, + 'sequence' => [ + [\T_RETURN], [\T_STRING, 'true'], ';', + [\T_RETURN], [\T_STRING, 'false'], ';', + ], + ], + [ + 'isNegative' => true, + 'sequence' => [ + [\T_RETURN], [\T_STRING, 'false'], ';', + [\T_RETURN], [\T_STRING, 'true'], ';', + ], + ], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Simplify `if` control structures that return the boolean result of their condition.', + [new CodeSample("isAllTokenKindsFound([\T_IF, \T_RETURN, \T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $slices = []; + + for ($ifIndex = $tokens->count() - 1; 0 <= $ifIndex; --$ifIndex) { + if (!$tokens[$ifIndex]->isGivenKind([\T_IF, \T_ELSEIF])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($ifIndex)]->equals(')')) { + continue; // in a loop without braces + } + + $startParenthesisIndex = $tokens->getNextTokenOfKind($ifIndex, ['(']); + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startParenthesisIndex); + $firstCandidateIndex = $tokens->getNextMeaningfulToken($endParenthesisIndex); + + foreach ($this->sequences as $sequenceSpec) { + $sequenceFound = $tokens->findSequence($sequenceSpec['sequence'], $firstCandidateIndex); + + if (null === $sequenceFound) { + continue; + } + + $firstSequenceIndex = array_key_first($sequenceFound); + + if ($firstSequenceIndex !== $firstCandidateIndex) { + continue; + } + + $indicesToClear = array_keys($sequenceFound); + array_pop($indicesToClear); // Preserve last semicolon + rsort($indicesToClear); + + foreach ($indicesToClear as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + $newTokens = [ + new Token([\T_RETURN, 'return']), + new Token([\T_WHITESPACE, ' ']), + ]; + + if ($sequenceSpec['isNegative']) { + $newTokens[] = new Token('!'); + } else { + $newTokens[] = new Token([\T_BOOL_CAST, '(bool)']); + } + + $slices[$ifIndex] = $newTokens; + $tokens->clearAt($ifIndex); + } + } + + if ([] !== $slices) { + $tokens->insertSlices($slices); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php new file mode 100644 index 0000000..981bb36 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.2. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SwitchCaseSemicolonToColonFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A case should be followed by a colon and not a semicolon.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_SWITCH); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + + if (null !== $default) { + $this->fixTokenIfNeeded($tokens, $default->getColonIndex()); + } + + foreach ($analysis->getCases() as $caseAnalysis) { + $this->fixTokenIfNeeded($tokens, $caseAnalysis->getColonIndex()); + } + } + } + + private function fixTokenIfNeeded(Tokens $tokens, int $index): void + { + if ($tokens[$index]->equals(';')) { + $tokens[$index] = new Token(':'); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php new file mode 100644 index 0000000..20b441a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶5.2. + * + * @author Sullivan Senechal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SwitchCaseSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra spaces between colon and case value.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_SWITCH); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + + if (null !== $default) { + $index = $default->getIndex(); + + if (!$tokens[$index + 1]->isWhitespace() || !$tokens[$index + 2]->equalsAny([':', ';'])) { + continue; + } + + $tokens->clearAt($index + 1); + } + + foreach ($analysis->getCases() as $caseAnalysis) { + $colonIndex = $caseAnalysis->getColonIndex(); + $valueIndex = $tokens->getPrevNonWhitespace($colonIndex); + + // skip if there is no space between the colon and previous token or is space after comment + if ($valueIndex === $colonIndex - 1 || $tokens[$valueIndex]->isComment()) { + continue; + } + + $tokens->clearAt($valueIndex + 1); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php new file mode 100644 index 0000000..8bb88dc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php @@ -0,0 +1,247 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SwitchContinueToBreakFixer extends AbstractFixer +{ + /** + * @var list + */ + private array $switchLevels = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Switch case must not be ended with `continue` but with `break`.', + [ + new CodeSample( + <<<'PHP' + 3) { + continue; + } + + continue 2; + } + } + + PHP, + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoAlternativeSyntaxFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_SWITCH, \T_CONTINUE]) && !$tokens->hasAlternativeSyntax(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $count = \count($tokens); + + for ($index = 1; $index < $count - 1; ++$index) { + $index = $this->doFix($tokens, $index, 0, false); + } + } + + /** + * @param int $depth >= 0 + */ + private function doFix(Tokens $tokens, int $index, int $depth, bool $isInSwitch): int + { + $token = $tokens[$index]; + + if ($token->isGivenKind([\T_FOREACH, \T_FOR, \T_WHILE])) { + // go to first `(`, go to its close ')', go to first of '{', ';', '? >' + $index = $tokens->getNextTokenOfKind($index, ['(']); + $index = $tokens->getNextTokenOfKind($index, [')']); + $index = $tokens->getNextTokenOfKind($index, ['{', ';', [\T_CLOSE_TAG]]); + + if (!$tokens[$index]->equals('{')) { + return $index; + } + + return $this->fixInLoop($tokens, $index, $depth + 1); + } + + if ($token->isGivenKind(\T_DO)) { + return $this->fixInLoop($tokens, $tokens->getNextTokenOfKind($index, ['{']), $depth + 1); + } + + if ($token->isGivenKind(\T_SWITCH)) { + return $this->fixInSwitch($tokens, $index, $depth + 1); + } + + if ($token->isGivenKind(\T_CONTINUE)) { + return $this->fixContinueWhenActsAsBreak($tokens, $index, $isInSwitch, $depth); + } + + return $index; + } + + private function fixInSwitch(Tokens $tokens, int $switchIndex, int $depth): int + { + $this->switchLevels[] = $depth; + + // figure out where the switch starts + $openIndex = $tokens->getNextTokenOfKind($switchIndex, ['{']); + + // figure out where the switch ends + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $openIndex); + + for ($index = $openIndex + 1; $index < $closeIndex; ++$index) { + $index = $this->doFix($tokens, $index, $depth, true); + } + + array_pop($this->switchLevels); + + return $closeIndex; + } + + private function fixInLoop(Tokens $tokens, int $openIndex, int $depth): int + { + $openCount = 1; + + while (true) { + ++$openIndex; + $token = $tokens[$openIndex]; + + if ($token->equals('{')) { + ++$openCount; + + continue; + } + + if ($token->equals('}')) { + --$openCount; + + if (0 === $openCount) { + break; + } + + continue; + } + + $openIndex = $this->doFix($tokens, $openIndex, $depth, false); + } + + return $openIndex; + } + + private function fixContinueWhenActsAsBreak(Tokens $tokens, int $continueIndex, bool $isInSwitch, int $depth): int + { + $followingContinueIndex = $tokens->getNextMeaningfulToken($continueIndex); + $followingContinueToken = $tokens[$followingContinueIndex]; + + if ($isInSwitch && $followingContinueToken->equals(';')) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); // short continue 1 notation + + return $followingContinueIndex; + } + + if (!$followingContinueToken->isGivenKind(\T_LNUMBER)) { + return $followingContinueIndex; + } + + $afterFollowingContinueIndex = $tokens->getNextMeaningfulToken($followingContinueIndex); + + if (!$tokens[$afterFollowingContinueIndex]->equals(';')) { + return $afterFollowingContinueIndex; // if next not is `;` return without fixing, for example `continue 1 ? >getContent(); + $jump = str_replace('_', '', $jump); // support for numeric_literal_separator + + if (\strlen($jump) > 2 && 'x' === $jump[1]) { + $jump = hexdec($jump); // hexadecimal - 0x1 + } elseif (\strlen($jump) > 2 && 'b' === $jump[1]) { + $jump = bindec($jump); // binary - 0b1 + } elseif (\strlen($jump) > 1 && '0' === $jump[0]) { + $jump = octdec($jump); // octal 01 + } elseif (Preg::match('#^\d+$#', $jump)) { // positive int + $jump = (float) $jump; // cast to float, might be a number bigger than PHP max. int value + } else { + return $afterFollowingContinueIndex; // cannot process value, ignore + } + + if ($jump > \PHP_INT_MAX) { + return $afterFollowingContinueIndex; // cannot process value, ignore + } + + $jump = (int) $jump; + + if ($isInSwitch && (1 === $jump || 0 === $jump)) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); // long continue 0/1 notation + + return $afterFollowingContinueIndex; + } + + $jumpDestination = $depth - $jump + 1; + + if (\in_array($jumpDestination, $this->switchLevels, true)) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); + + return $afterFollowingContinueIndex; + } + + return $afterFollowingContinueIndex; + } + + private function replaceContinueWithBreakToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([\T_BREAK, 'break']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php new file mode 100644 index 0000000..d6877da --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php @@ -0,0 +1,250 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * after_heredoc?: bool, + * elements?: list<'arguments'|'array_destructuring'|'arrays'|'match'|'parameters'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * after_heredoc: bool, + * elements: list<'arguments'|'array_destructuring'|'arrays'|'match'|'parameters'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TrailingCommaInMultilineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const ELEMENTS_ARRAYS = 'arrays'; + + /** + * @internal + */ + public const ELEMENTS_ARGUMENTS = 'arguments'; + + /** + * @internal + */ + public const ELEMENTS_PARAMETERS = 'parameters'; + + private const MATCH_EXPRESSIONS = 'match'; + + private const ARRAY_DESTRUCTURING = 'array_destructuring'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Arguments lists, array destructuring lists, arrays that are multi-line, `match`-lines and parameters lists must have a trailing comma.', + [ + new CodeSample(" true], + ), + new CodeSample(" [self::ELEMENTS_ARGUMENTS]]), + new VersionSpecificCodeSample(" [self::ELEMENTS_PARAMETERS]]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after MultilinePromotedPropertiesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN, '(', CT::T_DESTRUCTURING_BRACKET_OPEN]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('after_heredoc', 'Whether a trailing comma should also be placed after heredoc end.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + (new FixerOptionBuilder('elements', \sprintf('Where to fix multiline trailing comma (PHP >= 8.0 for `%s` and `%s`).', self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS))) // @TODO: remove text when PHP 8.0+ is required + ->setAllowedTypes(['string[]']) + ->setAllowedValues([ + new AllowedValueSubset([ + self::ARRAY_DESTRUCTURING, + self::ELEMENTS_ARGUMENTS, + self::ELEMENTS_ARRAYS, + self::ELEMENTS_PARAMETERS, + self::MATCH_EXPRESSIONS, + ]), + ]) + ->setDefault([self::ELEMENTS_ARRAYS]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $configuredElements = $this->configuration['elements']; + $fixArrays = \in_array(self::ELEMENTS_ARRAYS, $configuredElements, true); + $fixArguments = \in_array(self::ELEMENTS_ARGUMENTS, $configuredElements, true); + $fixParameters = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::ELEMENTS_PARAMETERS, $configuredElements, true); // @TODO: drop condition when PHP 8.0+ is required + $fixMatch = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::MATCH_EXPRESSIONS, $configuredElements, true); // @TODO: drop condition when PHP 8.0+ is required + $fixDestructuring = \in_array(self::ARRAY_DESTRUCTURING, $configuredElements, true); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind(CT::T_DESTRUCTURING_BRACKET_OPEN)) { + if ($fixDestructuring) { // array destructing short syntax + $this->fixBlock($tokens, $index); + } + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + if ($fixArrays) { // array short syntax + $this->fixBlock($tokens, $index); + } + + continue; + } + + if (!$tokens[$index]->equals('(')) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_ARRAY)) { + if ($fixArrays) { // array long syntax + $this->fixBlock($tokens, $index); + } + + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(\T_LIST)) { + if ($fixDestructuring || $fixArguments) { // array destructing long syntax + $this->fixBlock($tokens, $index); + } + + continue; + } + + if ($fixMatch && $tokens[$prevIndex]->isGivenKind(\T_MATCH)) { + $this->fixBlock($tokens, $tokens->getNextTokenOfKind($index, ['{'])); + + continue; + } + + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($fixArguments + && $tokens[$prevIndex]->equalsAny([']', [\T_CLASS], [\T_STRING], [\T_VARIABLE], [\T_STATIC], [\T_ISSET], [\T_UNSET], [\T_LIST]]) + && !$tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION) + ) { + $this->fixBlock($tokens, $index); + + continue; + } + + if ( + $fixParameters + && ( + $tokens[$prevIndex]->isGivenKind(\T_STRING) + && $tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION) + || $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]) + ) + ) { + $this->fixBlock($tokens, $index); + } + } + } + + private function fixBlock(Tokens $tokens, int $startIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + if (!$tokensAnalyzer->isBlockMultiline($tokens, $startIndex)) { + return; + } + + $blockType = Tokens::detectBlockType($tokens[$startIndex]); + $endIndex = $tokens->findBlockEnd($blockType['type'], $startIndex); + + $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); + if (!$tokens->isPartialCodeMultiline($beforeEndIndex, $endIndex)) { + return; + } + $beforeEndToken = $tokens[$beforeEndIndex]; + + // if there is some item between braces then add `,` after it + if ( + $startIndex !== $beforeEndIndex + && !$beforeEndToken->equalsAny([',', [CT::T_FIRST_CLASS_CALLABLE]]) + && (true === $this->configuration['after_heredoc'] || !$beforeEndToken->isGivenKind(\T_END_HEREDOC)) + ) { + $tokens->insertAt($beforeEndIndex + 1, new Token(',')); + + $endToken = $tokens[$endIndex]; + + if (!$endToken->isComment() && !$endToken->isWhitespace()) { + $tokens->ensureWhitespaceAtIndex($endIndex, 1, ' '); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php new file mode 100644 index 0000000..4f9e839 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php @@ -0,0 +1,760 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * always_move_variable?: bool, + * equal?: bool|null, + * identical?: bool|null, + * less_and_greater?: bool|null, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * always_move_variable: bool, + * equal: bool|null, + * identical: bool|null, + * less_and_greater: bool|null, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenKind from Token + * + * @author Bram Gotink + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array<_PhpTokenKind, Token> + */ + private array $candidatesMap; + + /** + * @var array<_PhpTokenKind, null|bool> + */ + private array $candidateTypesConfiguration; + + /** + * @var list<_PhpTokenKind> + */ + private array $candidateTypes; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.', + [ + new CodeSample( + <<<'PHP' + 3; // less than + + PHP, + [ + 'equal' => true, + 'identical' => false, + 'less_and_greater' => null, + ], + ), + new CodeSample( + <<<'PHP' + true, + ], + ), + new CodeSample( + <<<'PHP' + false, + 'identical' => false, + 'less_and_greater' => false, + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after IsNullFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->candidateTypes); + } + + protected function configurePostNormalisation(): void + { + $this->resolveConfiguration(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixTokens($tokens); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('equal', 'Style for equal (`==`, `!=`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('identical', 'Style for identical (`===`, `!==`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('less_and_greater', 'Style for less and greater than (`<`, `<=`, `>`, `>=`) statements.')) + ->setAllowedTypes(['bool', 'null']) + ->setDefault(null) + ->getOption(), + (new FixerOptionBuilder('always_move_variable', 'Whether variables should always be on non assignable side when applying Yoda style.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * Finds the end of the right-hand side of the comparison at the given + * index. + * + * The right-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The last index of the right-hand side of the comparison + */ + private function findComparisonEnd(Tokens $tokens, int $index): int + { + ++$index; + $count = \count($tokens); + + while ($index < $count) { + $token = $tokens[$index]; + + if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + ++$index; + + continue; + } + + if ($this->isOfLowerPrecedence($token)) { + break; + } + + $block = Tokens::detectBlockType($token); + + if (null === $block) { + ++$index; + + continue; + } + + if (!$block['isStart']) { + break; + } + + $index = $tokens->findBlockEnd($block['type'], $index) + 1; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$prev]->isGivenKind(\T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev; + } + + /** + * Finds the start of the left-hand side of the comparison at the given + * index. + * + * The left-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The first index of the left-hand side of the comparison + */ + private function findComparisonStart(Tokens $tokens, int $index): int + { + --$index; + $nonBlockFound = false; + + while (0 <= $index) { + $token = $tokens[$index]; + + if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + --$index; + + continue; + } + + if ($token->isGivenKind(CT::T_NAMED_ARGUMENT_COLON)) { + break; + } + + if ($this->isOfLowerPrecedence($token)) { + break; + } + + $block = Tokens::detectBlockType($token); + + if (null === $block) { + --$index; + $nonBlockFound = true; + + continue; + } + + if ( + $block['isStart'] + || ($nonBlockFound && Tokens::BLOCK_TYPE_BRACE === $block['type']) // closing of structure not related to the comparison + ) { + break; + } + + $index = $tokens->findBlockStart($block['type'], $index) - 1; + } + + return $tokens->getNextMeaningfulToken($index); + } + + private function fixTokens(Tokens $tokens): Tokens + { + for ($i = \count($tokens) - 1; $i > 1; --$i) { + if ($tokens[$i]->isGivenKind($this->candidateTypes)) { + \assert(isset($this->candidateTypesConfiguration[$tokens[$i]->getId()])); + $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getId()]; + } elseif ( + ($tokens[$i]->equals('<') && \in_array('<', $this->candidateTypes, true)) + || ($tokens[$i]->equals('>') && \in_array('>', $this->candidateTypes, true)) + ) { + \assert(isset($this->candidateTypesConfiguration[$tokens[$i]->getContent()])); + $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getContent()]; + } else { + continue; + } + + $fixableCompareInfo = $this->getCompareFixableInfo($tokens, $i, $yoda); + + if (null === $fixableCompareInfo) { + continue; + } + + $i = $this->fixTokensCompare( + $tokens, + $fixableCompareInfo['left']['start'], + $fixableCompareInfo['left']['end'], + $i, + $fixableCompareInfo['right']['start'], + $fixableCompareInfo['right']['end'], + ); + } + + return $tokens; + } + + /** + * Fixes the comparison at the given index. + * + * A comparison is considered fixed when + * - both sides are a variable (e.g. $a === $b) + * - neither side is a variable (e.g. self::CONST === 3) + * - only the right-hand side is a variable (e.g. 3 === self::$var) + * + * If the left-hand side and right-hand side of the given comparison are + * swapped, this function runs recursively on the previous left-hand-side. + * + * @return int an upper bound for all non-fixed comparisons + */ + private function fixTokensCompare( + Tokens $tokens, + int $startLeft, + int $endLeft, + int $compareOperatorIndex, + int $startRight, + int $endRight + ): int { + $type = $tokens[$compareOperatorIndex]->getId(); + $content = $tokens[$compareOperatorIndex]->getContent(); + + if (null !== $type && \array_key_exists($type, $this->candidatesMap)) { + $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type]; + } elseif (\array_key_exists($content, $this->candidatesMap)) { + $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content]; + } + + $right = $this->fixTokensComparePart($tokens, $startRight, $endRight); + $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft); + + for ($i = $startRight; $i <= $endRight; ++$i) { + $tokens->clearAt($i); + } + + for ($i = $startLeft; $i <= $endLeft; ++$i) { + $tokens->clearAt($i); + } + + $tokens->insertAt($startRight, $left); + $tokens->insertAt($startLeft, $right); + + return $startLeft; + } + + private function fixTokensComparePart(Tokens $tokens, int $start, int $end): Tokens + { + $newTokens = $tokens->generatePartialCode($start, $end); + $newTokens = $this->fixTokens(Tokens::fromCode(\sprintf('clearAt(\count($newTokens) - 1); + $newTokens->clearAt(0); + $newTokens->clearEmptyTokens(); + + return $newTokens; + } + + /** + * @return null|array{left: array{start: int, end: int}, right: array{start: int, end: int}} + */ + private function getCompareFixableInfo(Tokens $tokens, int $index, bool $yoda): ?array + { + $right = $this->getRightSideCompareFixableInfo($tokens, $index); + + if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) { + return null; + } + + $left = $this->getLeftSideCompareFixableInfo($tokens, $index); + + if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) { + return null; // do not fix lists assignment inside statements + } + + /** @var bool $strict */ + $strict = $this->configuration['always_move_variable']; + $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict); + $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict); + + if (!($leftSideIsVariable xor $rightSideIsVariable)) { + return null; // both are (not) variables, do not touch + } + + if (!$strict) { // special handling for braces with not "always_move_variable" + $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('('); + $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('('); + } + + return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable) + ? null + : ['left' => $left, 'right' => $right]; + } + + /** + * @return array{start: int, end: int} + */ + private function getLeftSideCompareFixableInfo(Tokens $tokens, int $index): array + { + return [ + 'start' => $this->findComparisonStart($tokens, $index), + 'end' => $tokens->getPrevMeaningfulToken($index), + ]; + } + + /** + * @return array{start: int, end: int} + */ + private function getRightSideCompareFixableInfo(Tokens $tokens, int $index): array + { + return [ + 'start' => $tokens->getNextMeaningfulToken($index), + 'end' => $this->findComparisonEnd($tokens, $index), + ]; + } + + private function isListStatement(Tokens $tokens, int $index, int $end): bool + { + for ($i = $index; $i <= $end; ++$i) { + if ($tokens[$i]->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_CLOSE])) { + return true; + } + } + + return false; + } + + /** + * Checks whether the given token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + * + * @param Token $token The token to check + * + * @return bool Whether the token has a lower precedence + */ + private function isOfLowerPrecedence(Token $token): bool + { + return $this->isOfLowerPrecedenceAssignment($token) + || $token->isGivenKind([ + \T_BOOLEAN_AND, // && + \T_BOOLEAN_OR, // || + \T_CASE, // case + \T_DOUBLE_ARROW, // => + \T_ECHO, // echo + \T_GOTO, // goto + \T_LOGICAL_AND, // and + \T_LOGICAL_OR, // or + \T_LOGICAL_XOR, // xor + \T_OPEN_TAG, // equalsAny([ + // bitwise and, or, xor + '&', '|', '^', + // ternary operators + '?', ':', + // end of PHP statement + ',', ';', + ]); + } + + /** + * Checks whether the given assignment token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + */ + private function isOfLowerPrecedenceAssignment(Token $token): bool + { + return $token->equals('=') || $token->isGivenKind([ + \T_AND_EQUAL, // &= + \T_CONCAT_EQUAL, // .= + \T_DIV_EQUAL, // /= + \T_MINUS_EQUAL, // -= + \T_MOD_EQUAL, // %= + \T_MUL_EQUAL, // *= + \T_OR_EQUAL, // |= + \T_PLUS_EQUAL, // += + \T_POW_EQUAL, // **= + \T_SL_EQUAL, // <<= + \T_SR_EQUAL, // >>= + \T_XOR_EQUAL, // ^= + \T_COALESCE_EQUAL, // ??= + ]); + } + + /** + * Checks whether the tokens between the given start and end describe a + * variable. + * + * @param Tokens $tokens The token list + * @param int $start The first index of the possible variable + * @param int $end The last index of the possible variable + * @param bool $strict Enable strict variable detection + * + * @return bool Whether the tokens describe a variable + */ + private function isVariable(Tokens $tokens, int $start, int $end, bool $strict): bool + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + + if ($start === $end) { + return $tokens[$start]->isGivenKind(\T_VARIABLE); + } + + if ($tokens[$start]->equals('(')) { + return true; + } + + if ($strict) { + for ($index = $start; $index <= $end; ++$index) { + if ( + $tokens[$index]->isCast() + || $tokens[$index]->isGivenKind(\T_INSTANCEOF) + || $tokens[$index]->equals('!') + || $tokenAnalyzer->isBinaryOperator($index) + ) { + return false; + } + } + } + + $index = $start; + + // handle multiple braces around statement ((($a === 1))) + while ( + $tokens[$index]->equals('(') + && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index) === $end + ) { + $index = $tokens->getNextMeaningfulToken($index); + $end = $tokens->getPrevMeaningfulToken($end); + } + + $expectString = false; + + while ($index <= $end) { + $current = $tokens[$index]; + if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) { + ++$index; + + continue; + } + + // check if this is the last token + if ($index === $end) { + return $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE); + } + + if ($current->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_CLOSE])) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $next = $tokens[$nextIndex]; + + // self:: or ClassName:: + if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_DOUBLE_COLON)) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + + continue; + } + + // \ClassName + if ($current->isGivenKind(\T_NS_SEPARATOR) && $next->isGivenKind(\T_STRING)) { + $index = $nextIndex; + + continue; + } + + // ClassName\ + if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_NS_SEPARATOR)) { + $index = $nextIndex; + + continue; + } + + // $a-> or a-> (as in $b->a->c) + if ($current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->isObjectOperator()) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + $expectString = true; + + continue; + } + + // $a[...], a[...] (as in $c->a[$b]), $a{...} or a{...} (as in $c->a{$b}) + if ( + $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE) + && $next->equalsAny(['[', [CT::T_ARRAY_INDEX_BRACE_OPEN, '{']]) + ) { + $index = $tokens->findBlockEnd( + $next->equals('[') ? Tokens::BLOCK_TYPE_INDEX_BRACKET : Tokens::BLOCK_TYPE_INDEX_BRACE, + $nextIndex, + ); + + if ($index === $end) { + return true; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->equalsAny(['[', [CT::T_ARRAY_INDEX_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + $expectString = true; + + continue; + } + + // $a(...) or $a->b(...) + if ($strict && $current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->equals('(')) { + return false; + } + + // {...} (as in $a->{$b}) + if ($expectString && $current->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index); + if ($index === $end) { + return true; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$index]->isObjectOperator()) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + $expectString = true; + + continue; + } + + break; + } + + return !$this->isConstant($tokens, $start, $end); + } + + private function isConstant(Tokens $tokens, int $index, int $end): bool + { + $expectArrayOnly = false; + $expectNumberOnly = false; + $expectNothing = false; + + for (; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ($token->isComment() || $token->isWhitespace()) { + continue; + } + + if ($expectNothing) { + return false; + } + + if ($expectArrayOnly) { + if ($token->equalsAny(['(', ')', [CT::T_ARRAY_BRACKET_CLOSE]])) { + continue; + } + + return false; + } + + if ($token->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + $expectArrayOnly = true; + + continue; + } + + if ($expectNumberOnly && !$token->isGivenKind([\T_LNUMBER, \T_DNUMBER])) { + return false; + } + + if ($token->equals('-')) { + $expectNumberOnly = true; + + continue; + } + + if ( + $token->isGivenKind([\T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING]) + || $token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']]) + ) { + $expectNothing = true; + + continue; + } + + return false; + } + + return true; + } + + private function resolveConfiguration(): void + { + $candidateTypes = []; + $this->candidatesMap = []; + + if (null !== $this->configuration['equal']) { + // `==`, `!=` and `<>` + $candidateTypes[\T_IS_EQUAL] = $this->configuration['equal']; + $candidateTypes[\T_IS_NOT_EQUAL] = $this->configuration['equal']; + } + + if (null !== $this->configuration['identical']) { + // `===` and `!==` + $candidateTypes[\T_IS_IDENTICAL] = $this->configuration['identical']; + $candidateTypes[\T_IS_NOT_IDENTICAL] = $this->configuration['identical']; + } + + if (null !== $this->configuration['less_and_greater']) { + // `<`, `<=`, `>` and `>=` + $candidateTypes[\T_IS_SMALLER_OR_EQUAL] = $this->configuration['less_and_greater']; + $this->candidatesMap[\T_IS_SMALLER_OR_EQUAL] = new Token([\T_IS_GREATER_OR_EQUAL, '>=']); + + $candidateTypes[\T_IS_GREATER_OR_EQUAL] = $this->configuration['less_and_greater']; + $this->candidatesMap[\T_IS_GREATER_OR_EQUAL] = new Token([\T_IS_SMALLER_OR_EQUAL, '<=']); + + $candidateTypes['<'] = $this->configuration['less_and_greater']; + $this->candidatesMap['<'] = new Token('>'); + + $candidateTypes['>'] = $this->configuration['less_and_greater']; + $this->candidatesMap['>'] = new Token('<'); + } + + $this->candidateTypesConfiguration = $candidateTypes; + $this->candidateTypes = array_keys($candidateTypes); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php new file mode 100644 index 0000000..6700ef7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface DeprecatedFixerInterface extends FixerInterface +{ + /** + * Returns names of fixers to use instead, if any. + * + * @return list + */ + public function getSuccessorsNames(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DocBlockAnnotationTrait.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DocBlockAnnotationTrait.php new file mode 100644 index 0000000..259c4c4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DocBlockAnnotationTrait.php @@ -0,0 +1,185 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @phpstan-require-implements FixerInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +trait DocBlockAnnotationTrait +{ + final protected function getDocBlockIndex(Tokens $tokens, int $index): int + { + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT, FCT::T_ATTRIBUTE, FCT::T_READONLY])); + + return $index; + } + + /** + * @param list $preventingAnnotations + * @param list $preventingAttributes + */ + final protected function ensureIsDocBlockWithAnnotation( + Tokens $tokens, + int $index, + string $annotation, + array $preventingAnnotations, + array $preventingAttributes + ): void { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + if ($this->isPreventedByAttribute($tokens, $index, $preventingAttributes)) { + return; + } + + if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + $this->updateDocBlockIfNeeded($tokens, $docBlockIndex, $annotation, $preventingAnnotations); + } else { + $this->createDocBlock($tokens, $docBlockIndex, $annotation); + } + } + + protected function createDocBlock(Tokens $tokens, int $docBlockIndex, string $annotation): void + { + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $toInsert = [ + new Token([\T_DOC_COMMENT, "/**{$lineEnd}{$originalIndent} * @{$annotation}{$lineEnd}{$originalIndent} */"]), + new Token([\T_WHITESPACE, $lineEnd.$originalIndent]), + ]; + $index = $tokens->getNextMeaningfulToken($docBlockIndex); + $tokens->insertAt($index, $toInsert); + + if (!$tokens[$index - 1]->isGivenKind(\T_WHITESPACE)) { + $extraNewLines = $this->whitespacesConfig->getLineEnding(); + + if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) { + $extraNewLines .= $this->whitespacesConfig->getLineEnding(); + } + + $tokens->insertAt($index, [ + new Token([\T_WHITESPACE, $extraNewLines.WhitespacesAnalyzer::detectIndent($tokens, $index)]), + ]); + } + } + + /** + * @param list $preventingAnnotations + */ + private function updateDocBlockIfNeeded( + Tokens $tokens, + int $docBlockIndex, + string $annotation, + array $preventingAnnotations + ): void { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + foreach ($preventingAnnotations as $preventingAnnotation) { + if ([] !== $doc->getAnnotationsOfType($preventingAnnotation)) { + return; + } + } + $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex, $annotation); + + $lines = $this->addAnnotation($doc, $tokens, $docBlockIndex, $annotation); + $lines = implode('', $lines); + + $tokens->getNamespaceDeclarations(); + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); + } + + /** + * @param list $preventingAttributes + */ + private function isPreventedByAttribute(Tokens $tokens, int $index, array $preventingAttributes): bool + { + if ([] === $preventingAttributes) { + return false; + } + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind([\T_FINAL, FCT::T_READONLY])); + if (!$tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + return false; + } + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); + + foreach (AttributeAnalyzer::collect($tokens, $index) as $attributeAnalysis) { + foreach ($attributeAnalysis->getAttributes() as $attribute) { + if (\in_array(strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)), $preventingAttributes, true)) { + return true; + } + } + } + + return false; + } + + /** + * @return non-empty-list + */ + private function addAnnotation( + DocBlock $docBlock, + Tokens $tokens, + int $docBlockIndex, + string $annotation + ): array { + $lines = $docBlock->getLines(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + array_splice($lines, -1, 0, [new Line($originalIndent.' * @'.$annotation.$lineEnd)]); + + return $lines; + } + + private function makeDocBlockMultiLineIfNeeded( + DocBlock $doc, + Tokens $tokens, + int $docBlockIndex, + string $annotation + ): DocBlock { + $lines = $doc->getLines(); + if (1 === \count($lines) && [] === $doc->getAnnotationsOfType($annotation)) { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding()); + + return $doc; + } + + return $doc; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php new file mode 100644 index 0000000..6e0bbaa --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Forces the configured operator for assignment in arrays in Doctrine Annotations. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ignored_tags?: list, + * operator?: ':'|'=', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ignored_tags: list, + * operator: ':'|'=', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DoctrineAnnotationArrayAssignmentFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations must use configured operator for assignment in arrays.', + [ + new CodeSample( + " ':'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before DoctrineAnnotationSpacesFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $options = parent::createConfigurationDefinition()->getOptions(); + + $options[] = (new FixerOptionBuilder('operator', 'The operator to use.')) + ->setAllowedValues(['=', ':']) + ->setDefault('=') + ->getOption() + ; + + return new FixerConfigurationResolver($options); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + $scopes = []; + foreach ($doctrineAnnotationTokens as $token) { + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $scopes[] = 'annotation'; + + continue; + } + + if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) { + $scopes[] = 'array'; + + continue; + } + + if ($token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { + array_pop($scopes); + + continue; + } + + if ('array' === end($scopes) && $token->isType([DocLexer::T_EQUALS, DocLexer::T_COLON])) { + $token->setContent($this->configuration['operator']); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php new file mode 100644 index 0000000..48ddeb5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php @@ -0,0 +1,134 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * Adds braces to Doctrine annotations when missing. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ignored_tags?: list, + * syntax?: 'with_braces'|'without_braces', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ignored_tags: list, + * syntax: 'with_braces'|'without_braces', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations without arguments must use the configured syntax.', + [ + new CodeSample( + " 'with_braces'], + ), + ], + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('syntax', 'Whether to add or remove braces.')) + ->setAllowedValues(['with_braces', 'without_braces']) + ->setDefault('without_braces') + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + if ('without_braces' === $this->configuration['syntax']) { + $this->removesBracesFromAnnotations($doctrineAnnotationTokens); + } else { + $this->addBracesToAnnotations($doctrineAnnotationTokens); + } + } + + private function addBracesToAnnotations(Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isType(DocLexer::T_AT)) { + continue; + } + + $braceIndex = $tokens->getNextMeaningfulToken($index + 1); + if (null !== $braceIndex && $tokens[$braceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + continue; + } + + $tokens->insertAt($index + 2, new Token(DocLexer::T_OPEN_PARENTHESIS, '(')); + $tokens->insertAt($index + 3, new Token(DocLexer::T_CLOSE_PARENTHESIS, ')')); + } + } + + private function removesBracesFromAnnotations(Tokens $tokens): void + { + for ($index = 0, $max = \count($tokens); $index < $max; ++$index) { + if (!$tokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + + $openBraceIndex = $tokens->getNextMeaningfulToken($index + 1); + if (null === $openBraceIndex) { + continue; + } + + if (!$tokens[$openBraceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { + continue; + } + + $closeBraceIndex = $tokens->getNextMeaningfulToken($openBraceIndex); + if (null === $closeBraceIndex) { + continue; + } + + if (!$tokens[$closeBraceIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { + continue; + } + + for ($currentIndex = $index + 2; $currentIndex <= $closeBraceIndex; ++$currentIndex) { + $tokens[$currentIndex]->clear(); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php new file mode 100644 index 0000000..1d08378 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php @@ -0,0 +1,201 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * ignored_tags?: list, + * indent_mixed_lines?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * ignored_tags: list, + * indent_mixed_lines: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DoctrineAnnotationIndentationFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Doctrine annotations must be indented with four spaces.', + [ + new CodeSample(" true], + ), + ], + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('indent_mixed_lines', 'Whether to indent lines that have content before closing parenthesis.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + $annotationPositions = []; + for ($index = 0, $max = \count($doctrineAnnotationTokens); $index < $max; ++$index) { + if (!$doctrineAnnotationTokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + + $annotationEndIndex = $doctrineAnnotationTokens->getAnnotationEnd($index); + if (null === $annotationEndIndex) { + return; + } + + $annotationPositions[] = [$index, $annotationEndIndex]; + $index = $annotationEndIndex; + } + + $indentLevel = 0; + foreach ($doctrineAnnotationTokens as $index => $token) { + if (!$token->isType(DocLexer::T_NONE) || !str_contains($token->getContent(), "\n")) { + continue; + } + + if (!$this->indentationCanBeFixed($doctrineAnnotationTokens, $index, $annotationPositions)) { + continue; + } + + $braces = $this->getLineBracesCount($doctrineAnnotationTokens, $index); + $delta = $braces[0] - $braces[1]; + $mixedBraces = 0 === $delta && $braces[0] > 0; + $extraIndentLevel = 0; + + if ($indentLevel > 0 && ($delta < 0 || $mixedBraces)) { + --$indentLevel; + + if (true === $this->configuration['indent_mixed_lines'] && $this->isClosingLineWithMeaningfulContent($doctrineAnnotationTokens, $index)) { + $extraIndentLevel = 1; + } + } + + $token->setContent(Preg::replace( + '/(\n( +\*)?) *$/', + '$1'.str_repeat(' ', 4 * ($indentLevel + $extraIndentLevel) + 1), + $token->getContent(), + )); + + if ($delta > 0 || $mixedBraces) { + ++$indentLevel; + } + } + } + + /** + * @return array{int, int} + */ + private function getLineBracesCount(Tokens $tokens, int $index): array + { + $opening = 0; + $closing = 0; + + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE) && str_contains($token->getContent(), "\n")) { + break; + } + + if ($token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_OPEN_CURLY_BRACES])) { + ++$opening; + + continue; + } + + if (!$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) { + continue; + } + + if ($opening > 0) { + --$opening; + } else { + ++$closing; + } + } + + return [$opening, $closing]; + } + + private function isClosingLineWithMeaningfulContent(Tokens $tokens, int $index): bool + { + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE)) { + if (str_contains($token->getContent(), "\n")) { + return false; + } + + continue; + } + + return !$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES]); + } + + return false; + } + + /** + * @param list $annotationPositions Pairs of begin and end indices of main annotations + */ + private function indentationCanBeFixed(Tokens $tokens, int $newLineTokenIndex, array $annotationPositions): bool + { + foreach ($annotationPositions as $position) { + if ($newLineTokenIndex >= $position[0] && $newLineTokenIndex <= $position[1]) { + return true; + } + } + + for ($index = $newLineTokenIndex + 1, $max = \count($tokens); $index < $max; ++$index) { + $token = $tokens[$index]; + + if (str_contains($token->getContent(), "\n")) { + return false; + } + + return $tokens[$index]->isType(DocLexer::T_AT); + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php new file mode 100644 index 0000000..cb2adde --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php @@ -0,0 +1,322 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\DocLexer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * Fixes spaces around commas and assignment operators in Doctrine annotations. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * after_argument_assignments?: bool|null, + * after_array_assignments_colon?: bool|null, + * after_array_assignments_equals?: bool|null, + * around_commas?: bool, + * around_parentheses?: bool, + * before_argument_assignments?: bool|null, + * before_array_assignments_colon?: bool|null, + * before_array_assignments_equals?: bool|null, + * ignored_tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * after_argument_assignments: bool|null, + * after_array_assignments_colon: bool|null, + * after_array_assignments_equals: bool|null, + * around_commas: bool, + * around_parentheses: bool, + * before_argument_assignments: bool|null, + * before_array_assignments_colon: bool|null, + * before_array_assignments_equals: bool|null, + * ignored_tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DoctrineAnnotationSpacesFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes spaces in Doctrine annotations.', + [ + new CodeSample( + " false, 'before_array_assignments_equals' => false], + ), + ], + 'There must not be any space around parentheses; commas must be preceded by no space and followed by one space; there must be no space around named arguments assignment operator; there must be one space around array assignment operator.', + ); + } + + /** + * {@inheritdoc} + * + * Must run after DoctrineAnnotationArrayAssignmentFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + ...parent::createConfigurationDefinition()->getOptions(), + (new FixerOptionBuilder('around_parentheses', 'Whether to fix spaces around parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('around_commas', 'Whether to fix spaces around commas.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('before_argument_assignments', 'Whether to add, remove or ignore spaces before argument assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('after_argument_assignments', 'Whether to add, remove or ignore spaces after argument assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('before_array_assignments_equals', 'Whether to add, remove or ignore spaces before array `=` assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('after_array_assignments_equals', 'Whether to add, remove or ignore spaces after array assignment `=` operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('before_array_assignments_colon', 'Whether to add, remove or ignore spaces before array `:` assignment operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('after_array_assignments_colon', 'Whether to add, remove or ignore spaces after array assignment `:` operator.')) + ->setAllowedTypes(['null', 'bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void + { + if (true === $this->configuration['around_parentheses']) { + $this->fixSpacesAroundParentheses($doctrineAnnotationTokens); + } + + if (true === $this->configuration['around_commas']) { + $this->fixSpacesAroundCommas($doctrineAnnotationTokens); + } + + if ( + null !== $this->configuration['before_argument_assignments'] + || null !== $this->configuration['after_argument_assignments'] + || null !== $this->configuration['before_array_assignments_equals'] + || null !== $this->configuration['after_array_assignments_equals'] + || null !== $this->configuration['before_array_assignments_colon'] + || null !== $this->configuration['after_array_assignments_colon'] + ) { + $this->fixAroundAssignments($doctrineAnnotationTokens); + } + } + + private function fixSpacesAroundParentheses(Tokens $tokens): void + { + $inAnnotationUntilIndex = null; + + foreach ($tokens as $index => $token) { + if (null !== $inAnnotationUntilIndex) { + if ($index === $inAnnotationUntilIndex) { + $inAnnotationUntilIndex = null; + + continue; + } + } elseif ($token->isType(DocLexer::T_AT)) { + $endIndex = $tokens->getAnnotationEnd($index); + if (null !== $endIndex) { + $inAnnotationUntilIndex = $endIndex + 1; + } + + continue; + } + + if (null === $inAnnotationUntilIndex) { + continue; + } + + if (!$token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_CLOSE_PARENTHESIS])) { + continue; + } + + if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { + $token = $tokens[$index - 1]; + if ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + + $token = $tokens[$index + 1]; + } else { + $token = $tokens[$index - 1]; + } + + if ($token->isType(DocLexer::T_NONE)) { + if (str_contains($token->getContent(), "\n")) { + continue; + } + + $token->clear(); + } + } + } + + private function fixSpacesAroundCommas(Tokens $tokens): void + { + $inAnnotationUntilIndex = null; + + foreach ($tokens as $index => $token) { + if (null !== $inAnnotationUntilIndex) { + if ($index === $inAnnotationUntilIndex) { + $inAnnotationUntilIndex = null; + + continue; + } + } elseif ($token->isType(DocLexer::T_AT)) { + $endIndex = $tokens->getAnnotationEnd($index); + if (null !== $endIndex) { + $inAnnotationUntilIndex = $endIndex; + } + + continue; + } + + if (null === $inAnnotationUntilIndex) { + continue; + } + + if (!$token->isType(DocLexer::T_COMMA)) { + continue; + } + + $token = $tokens[$index - 1]; + if ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + + if ($index < \count($tokens) - 1 && !Preg::match('/^\s/', $tokens[$index + 1]->getContent())) { + $tokens->insertAt($index + 1, new Token(DocLexer::T_NONE, ' ')); + } + } + } + + private function fixAroundAssignments(Tokens $tokens): void + { + $beforeArguments = $this->configuration['before_argument_assignments']; + $afterArguments = $this->configuration['after_argument_assignments']; + $beforeArraysEquals = $this->configuration['before_array_assignments_equals']; + $afterArraysEquals = $this->configuration['after_array_assignments_equals']; + $beforeArraysColon = $this->configuration['before_array_assignments_colon']; + $afterArraysColon = $this->configuration['after_array_assignments_colon']; + + $scopes = []; + foreach ($tokens as $index => $token) { + $endScopeType = end($scopes); + if (false !== $endScopeType && $token->isType($endScopeType)) { + array_pop($scopes); + + continue; + } + + if ($token->isType(DocLexer::T_AT)) { + $scopes[] = DocLexer::T_CLOSE_PARENTHESIS; + + continue; + } + + if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) { + $scopes[] = DocLexer::T_CLOSE_CURLY_BRACES; + + continue; + } + + if (DocLexer::T_CLOSE_PARENTHESIS === $endScopeType && $token->isType(DocLexer::T_EQUALS)) { + $this->updateSpacesAfter($tokens, $index, $afterArguments); + $this->updateSpacesBefore($tokens, $index, $beforeArguments); + + continue; + } + + if (DocLexer::T_CLOSE_CURLY_BRACES === $endScopeType) { + if ($token->isType(DocLexer::T_EQUALS)) { + $this->updateSpacesAfter($tokens, $index, $afterArraysEquals); + $this->updateSpacesBefore($tokens, $index, $beforeArraysEquals); + + continue; + } + + if ($token->isType(DocLexer::T_COLON)) { + $this->updateSpacesAfter($tokens, $index, $afterArraysColon); + $this->updateSpacesBefore($tokens, $index, $beforeArraysColon); + } + } + } + } + + private function updateSpacesAfter(Tokens $tokens, int $index, ?bool $insert): void + { + $this->updateSpacesAt($tokens, $index + 1, $index + 1, $insert); + } + + private function updateSpacesBefore(Tokens $tokens, int $index, ?bool $insert): void + { + $this->updateSpacesAt($tokens, $index - 1, $index, $insert); + } + + private function updateSpacesAt(Tokens $tokens, int $index, int $insertIndex, ?bool $insert): void + { + if (null === $insert) { + return; + } + + $token = $tokens[$index]; + if ($insert) { + if (!$token->isType(DocLexer::T_NONE)) { + $tokens->insertAt($insertIndex, $token = new Token()); + } + + $token->setContent(' '); + } elseif ($token->isType(DocLexer::T_NONE)) { + $token->clear(); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ExperimentalFixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ExperimentalFixerInterface.php new file mode 100644 index 0000000..4f9ae54 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ExperimentalFixerInterface.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ExperimentalFixerInterface extends FixerInterface {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php new file mode 100644 index 0000000..01d1182 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * @author Fabien Potencier + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FixerInterface +{ + /** + * Check if the fixer is a candidate for given Tokens collection. + * + * Fixer is a candidate when the collection contains tokens that may be fixed + * during fixer work. This could be considered as some kind of bloom filter. + * When this method returns true then to the Tokens collection may or may not + * need a fixing, but when this method returns false then the Tokens collection + * need no fixing for sure. + */ + public function isCandidate(Tokens $tokens): bool; + + /** + * Check if fixer is risky or not. + * + * Risky fixer could change code behaviour! + */ + public function isRisky(): bool; + + /** + * Fixes a file. + * + * @param \SplFileInfo $file A \SplFileInfo instance + * @param Tokens $tokens Tokens collection + */ + public function fix(\SplFileInfo $file, Tokens $tokens): void; + + /** + * Returns the definition of the fixer. + */ + public function getDefinition(): FixerDefinitionInterface; + + /** + * Returns the name of the fixer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName(): string; + + /** + * Returns the priority of the fixer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority(): int; + + /** + * Returns true if the file is supported by this fixer. + * + * @return bool true if the file is supported by this fixer, false otherwise + */ + public function supports(\SplFileInfo $file): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php new file mode 100644 index 0000000..8587d93 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php @@ -0,0 +1,226 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CombineNestedDirnameFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace multiple nested calls of `dirname` by only one call with second `$level` parameter.', + [ + new CodeSample( + "isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + * Must run after DirConstantFixer. + */ + public function getPriority(): int + { + return 35; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $dirnameInfo = $this->getDirnameInfo($tokens, $index); + + if (false === $dirnameInfo) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); + + if (!$tokens[$prev]->equals('(')) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($prev); + $firstArgumentEnd = $dirnameInfo['end']; + $dirnameInfoArray = [$dirnameInfo]; + + while (($dirnameInfo = $this->getDirnameInfo($tokens, $prev, $firstArgumentEnd)) !== false) { + $dirnameInfoArray[] = $dirnameInfo; + $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); + + if (!$tokens[$prev]->equals('(')) { + break; + } + + $prev = $tokens->getPrevMeaningfulToken($prev); + $firstArgumentEnd = $dirnameInfo['end']; + } + + if (\count($dirnameInfoArray) > 1) { + $this->combineDirnames($tokens, $dirnameInfoArray); + } + + $index = $prev; + } + } + + /** + * @param int $index Index of `dirname` + * @param null|int $firstArgumentEndIndex Index of last token of first argument of `dirname` call + * + * @return array{indices: non-empty-list, secondArgument?: int, levels: int, end: int}|false `false` when it is not a (supported) `dirname` call, an array with info about the dirname call otherwise + */ + private function getDirnameInfo(Tokens $tokens, int $index, ?int $firstArgumentEndIndex = null) + { + if (!$tokens[$index]->equals([\T_STRING, 'dirname'], false)) { + return false; + } + + if (!(new FunctionsAnalyzer())->isGlobalFunctionCall($tokens, $index)) { + return false; + } + + $info = ['indices' => []]; + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(\T_NS_SEPARATOR)) { + $info['indices'][] = $prev; + } + + $info['indices'][] = $index; + + // opening parenthesis "(" + $next = $tokens->getNextMeaningfulToken($index); + $info['indices'][] = $next; + + if (null !== $firstArgumentEndIndex) { + $next = $tokens->getNextMeaningfulToken($firstArgumentEndIndex); + } else { + $next = $tokens->getNextMeaningfulToken($next); + + if ($tokens[$next]->equals(')')) { + return false; + } + + while (!$tokens[$next]->equalsAny([',', ')'])) { + $blockType = Tokens::detectBlockType($tokens[$next]); + + if (null !== $blockType) { + $next = $tokens->findBlockEnd($blockType['type'], $next); + } + + $next = $tokens->getNextMeaningfulToken($next); + } + } + + $info['indices'][] = $next; + + if ($tokens[$next]->equals(',')) { + $next = $tokens->getNextMeaningfulToken($next); + $info['indices'][] = $next; + } + + if ($tokens[$next]->equals(')')) { + $info['levels'] = 1; + $info['end'] = $next; + + return $info; + } + + if (!$tokens[$next]->isGivenKind(\T_LNUMBER)) { + return false; + } + + $info['secondArgument'] = $next; + $info['levels'] = (int) $tokens[$next]->getContent(); + + $next = $tokens->getNextMeaningfulToken($next); + + if ($tokens[$next]->equals(',')) { + $info['indices'][] = $next; + $next = $tokens->getNextMeaningfulToken($next); + } + + if (!$tokens[$next]->equals(')')) { + return false; + } + + $info['indices'][] = $next; + $info['end'] = $next; + + return $info; + } + + /** + * @param non-empty-list, secondArgument?: int, levels: int, end: int}> $dirnameInfoArray + */ + private function combineDirnames(Tokens $tokens, array $dirnameInfoArray): void + { + $outerDirnameInfo = array_pop($dirnameInfoArray); + $levels = $outerDirnameInfo['levels']; + + foreach ($dirnameInfoArray as $dirnameInfo) { + $levels += $dirnameInfo['levels']; + + foreach ($dirnameInfo['indices'] as $index) { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + $levelsToken = new Token([\T_LNUMBER, (string) $levels]); + + if (isset($outerDirnameInfo['secondArgument'])) { + $tokens[$outerDirnameInfo['secondArgument']] = $levelsToken; + } else { + $prev = $tokens->getPrevMeaningfulToken($outerDirnameInfo['end']); + $items = []; + + if (!$tokens[$prev]->equals(',')) { + $items = [new Token(','), new Token([\T_WHITESPACE, ' '])]; + } + + $items[] = $levelsToken; + $tokens->insertAt($outerDirnameInfo['end'], $items); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php new file mode 100644 index 0000000..b9a10ba --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php @@ -0,0 +1,167 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DateTimeCreateFromFormatCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The first argument of `DateTime::createFromFormat` method must start with `!`.', + [ + new CodeSample("isTokenKindFound(\T_DOUBLE_COLON); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $scopeStartIndex = $namespace->getScopeStartIndex(); + $useDeclarations = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + + for ($index = $namespace->getScopeEndIndex(); $index > $scopeStartIndex; --$index) { + if (!$tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$functionNameIndex]->equals([\T_STRING, 'createFromFormat'], false)) { + continue; + } + + if (!$tokens[$tokens->getNextMeaningfulToken($functionNameIndex)]->equals('(')) { + continue; + } + + $classNameIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$classNameIndex]->equalsAny([[\T_STRING, \DateTime::class], [\T_STRING, \DateTimeImmutable::class]], false)) { + continue; + } + + $preClassNameIndex = $tokens->getPrevMeaningfulToken($classNameIndex); + + if ($tokens[$preClassNameIndex]->isGivenKind(\T_NS_SEPARATOR)) { + if ($tokens[$tokens->getPrevMeaningfulToken($preClassNameIndex)]->isGivenKind(\T_STRING)) { + continue; + } + } elseif (!$namespace->isGlobalNamespace()) { + continue; + } else { + foreach ($useDeclarations as $useDeclaration) { + foreach (['datetime', 'datetimeimmutable'] as $name) { + if ($name === strtolower($useDeclaration->getShortName()) && $name !== strtolower($useDeclaration->getFullName())) { + continue 3; + } + } + } + } + + $openIndex = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + + $argumentIndex = $this->getFirstArgumentTokenIndex($tokens, $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex)); + + if (null === $argumentIndex) { + continue; + } + + $format = $tokens[$argumentIndex]->getContent(); + + if (\strlen($format) < 3) { + continue; + } + + $offset = 'b' === $format[0] || 'B' === $format[0] ? 2 : 1; + + if ('!' === $format[$offset]) { + continue; + } + + $tokens->clearAt($argumentIndex); + $tokens->insertAt($argumentIndex, new Token([\T_CONSTANT_ENCAPSED_STRING, substr_replace($format, '!', $offset, 0)])); + } + } + } + + /** + * @param array $arguments + */ + private function getFirstArgumentTokenIndex(Tokens $tokens, array $arguments): ?int + { + if (2 !== \count($arguments)) { + return null; + } + + $argumentStartIndex = array_key_first($arguments); + $argumentEndIndex = $arguments[$argumentStartIndex]; + $argumentStartIndex = $tokens->getNextMeaningfulToken($argumentStartIndex - 1); + + if ( + $argumentStartIndex !== $argumentEndIndex + && $tokens->getNextMeaningfulToken($argumentStartIndex) <= $argumentEndIndex + ) { + return null; // argument is not a simple single string + } + + return !$tokens[$argumentStartIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) + ? null // first argument is not a string + : $argumentStartIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php new file mode 100644 index 0000000..2cfcbc0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php @@ -0,0 +1,126 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FopenFlagOrderFixer extends AbstractFopenFlagFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Order the flags in `fopen` calls, `b` and `t` must be last.', + [new CodeSample("isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + + if (null !== $argumentFlagIndex) { + return; // multiple meaningful tokens found, no candidate for fixing + } + + $argumentFlagIndex = $i; + } + + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + return; + } + + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; // `'`, `"`, `b` or `B` + + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; // `'` or `"` + $mode = substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = substr($content, 1, -1); + } + + $modeLength = \strlen($mode); + if ($modeLength < 2) { + return; // nothing to sort + } + + if (false === $this->isValidModeString($mode)) { + return; + } + + $split = $this->sortFlags(Preg::split('#([^\+]\+?)#', $mode, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE)); + $newContent = $binPrefix.$contentQuote.implode('', $split).$contentQuote; + + if ($content !== $newContent) { + $tokens[$argumentFlagIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, $newContent]); + } + } + + /** + * @param list $flags + * + * @return list + */ + private function sortFlags(array $flags): array + { + usort( + $flags, + static function (string $flag1, string $flag2): int { + if ($flag1 === $flag2) { + return 0; + } + + if ('b' === $flag1) { + return 1; + } + + if ('b' === $flag2) { + return -1; + } + + if ('t' === $flag1) { + return 1; + } + + if ('t' === $flag2) { + return -1; + } + + return $flag1 < $flag2 ? -1 : 1; + }, + ); + + return $flags; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php new file mode 100644 index 0000000..72e0deb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * b_mode?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * b_mode: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FopenFlagsFixer extends AbstractFopenFlagFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The flags in `fopen` calls must omit `t`, and `b` must be omitted or included consistently.', + [ + new CodeSample(" false]), + ], + null, + 'Risky when the function `fopen` is overridden.', + ); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('b_mode', 'The `b` flag must be used (`true`) or omitted (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void + { + $argumentFlagIndex = null; + + for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + + if (null !== $argumentFlagIndex) { + return; // multiple meaningful tokens found, no candidate for fixing + } + + $argumentFlagIndex = $i; + } + + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + return; + } + + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; // `'`, `"`, `b` or `B` + + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; // `'` or `"` + $mode = substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = substr($content, 1, -1); + } + + if (false === $this->isValidModeString($mode)) { + return; + } + + $mode = str_replace('t', '', $mode); + + if (true === $this->configuration['b_mode']) { + if (!str_contains($mode, 'b')) { + $mode .= 'b'; + } + } else { + $mode = str_replace('b', '', $mode); + } + + $newContent = $binPrefix.$contentQuote.$mode.$contentQuote; + + if ($content !== $newContent) { + $tokens[$argumentFlagIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, $newContent]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php new file mode 100644 index 0000000..6f3c3da --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php @@ -0,0 +1,277 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 generally (¶1 and ¶6). + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * closure_fn_spacing?: 'none'|'one', + * closure_function_spacing?: 'none'|'one', + * trailing_comma_single_line?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * closure_fn_spacing: 'none'|'one', + * closure_function_spacing: 'none'|'one', + * trailing_comma_single_line: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FunctionDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const SPACING_NONE = 'none'; + + /** + * @internal + */ + public const SPACING_ONE = 'one'; + + private const SUPPORTED_SPACINGS = [self::SPACING_NONE, self::SPACING_ONE]; + + private string $singleLineWhitespaceOptions = " \t"; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Spaces should be properly placed in a function declaration.', + [ + new CodeSample( + <<<'PHP' + self::SPACING_NONE], + ), + new CodeSample( + <<<'PHP' + null; + + PHP, + ['closure_fn_spacing' => self::SPACING_NONE], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, UseArrowFunctionsFixer. + */ + public function getPriority(): int + { + return 31; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind([\T_FUNCTION, \T_FN])) { + continue; + } + + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', [\T_CLOSE_TAG]]); + + if (!$tokens[$startParenthesisIndex]->equals('(')) { + continue; + } + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startParenthesisIndex); + + if (false === $this->configuration['trailing_comma_single_line'] + && !$tokens->isPartialCodeMultiline($index, $endParenthesisIndex) + ) { + $commaIndex = $tokens->getPrevMeaningfulToken($endParenthesisIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + + $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{', [\T_DOUBLE_ARROW]]); + + // fix single-line whitespace before { or => + // eg: `function foo(){}` => `function foo() {}` + // eg: `function foo() {}` => `function foo() {}` + // eg: `fn() =>` => `fn() =>` + if ( + $tokens[$startBraceIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]]) + && ( + !$tokens[$startBraceIndex - 1]->isWhitespace() + || $tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions) + ) + ) { + $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); + } + + $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); + $afterParenthesisToken = $tokens[$afterParenthesisIndex]; + + if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { + // fix whitespace after CT:T_USE_LAMBDA (we might add a token, so do this before determining start and end parenthesis) + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' '); + + $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); + $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $useStartParenthesisIndex); + + if (false === $this->configuration['trailing_comma_single_line'] + && !$tokens->isPartialCodeMultiline($index, $useEndParenthesisIndex) + ) { + $commaIndex = $tokens->getPrevMeaningfulToken($useEndParenthesisIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + + // remove single-line edge whitespaces inside use parentheses + $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); + + // fix whitespace before CT::T_USE_LAMBDA + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' '); + } + + // remove single-line edge whitespaces inside parameters list parentheses + $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex); + $isLambda = $tokensAnalyzer->isLambda($index); + + // remove whitespace before ( + // eg: `function foo () {}` => `function foo() {}` + if (!$isLambda && $tokens[$startParenthesisIndex - 1]->isWhitespace() && !$tokens[$tokens->getPrevNonWhitespace($startParenthesisIndex - 1)]->isComment()) { + $tokens->clearAt($startParenthesisIndex - 1); + } + + $option = $token->isGivenKind(\T_FN) ? 'closure_fn_spacing' : 'closure_function_spacing'; + + if ($isLambda && self::SPACING_NONE === $this->configuration[$option]) { + // optionally remove whitespace after T_FUNCTION of a closure + // eg: `function () {}` => `function() {}` + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } else { + // otherwise, enforce whitespace after T_FUNCTION + // eg: `function foo() {}` => `function foo() {}` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + + if ($isLambda) { + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(\T_STATIC)) { + // fix whitespace after T_STATIC + // eg: `$a = static function(){};` => `$a = static function(){};` + $tokens->ensureWhitespaceAtIndex($prev + 1, 0, ' '); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('closure_function_spacing', 'Spacing to use before open parenthesis for closures.')) + ->setDefault(self::SPACING_ONE) + ->setAllowedValues(self::SUPPORTED_SPACINGS) + ->getOption(), + (new FixerOptionBuilder('closure_fn_spacing', 'Spacing to use before open parenthesis for short arrow functions.')) + ->setDefault( + Future::getV4OrV3( + self::SPACING_NONE, + self::SPACING_ONE, + ), + ) + ->setAllowedValues(self::SUPPORTED_SPACINGS) + ->getOption(), + (new FixerOptionBuilder('trailing_comma_single_line', 'Whether trailing commas are allowed in single line signatures.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void + { + do { + --$end; + } while ($tokens->isEmptyAt($end)); + + // remove single-line whitespace before `)` + if ($tokens[$end]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($end); + } + + // remove single-line whitespace after `(` + if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($start + 1); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php new file mode 100644 index 0000000..1a2f4c9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\Whitespace\TypeDeclarationSpacesFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @deprecated + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FunctionTypehintSpaceFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure single space between function\'s argument and its typehint.', + [ + new CodeSample("isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new TypeDeclarationSpacesFixer(); + $fixer->configure(['elements' => ['function']]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php new file mode 100644 index 0000000..e2a4d0d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php @@ -0,0 +1,143 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ImplodeCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Function `implode` must be called with 2 arguments in the documented order.', + [ + new CodeSample("isTokenKindFound(\T_STRING); + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after NoAliasFunctionsFixer. + */ + public function getPriority(): int + { + return 37; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals([\T_STRING, 'implode'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $argumentsIndices = $this->getArgumentIndices($tokens, $index); + + if (1 === \count($argumentsIndices)) { + $firstArgumentIndex = array_key_first($argumentsIndices); + $tokens->insertAt($firstArgumentIndex, [ + new Token([\T_CONSTANT_ENCAPSED_STRING, "''"]), + new Token(','), + new Token([\T_WHITESPACE, ' ']), + ]); + + continue; + } + + if (2 === \count($argumentsIndices)) { + \assert(isset(array_keys($argumentsIndices)[0], array_keys($argumentsIndices)[1])); + [$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices); + + // If the first argument is string we have nothing to do + if ($tokens[$firstArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + // If the second argument is not string we cannot make a swap + if (!$tokens[$secondArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + // collect tokens from first argument + \assert(isset($argumentsIndices[key($argumentsIndices)])); + $firstArgumentEndIndex = $argumentsIndices[key($argumentsIndices)]; + $newSecondArgumentTokens = []; + for ($i = array_key_first($argumentsIndices); $i <= $firstArgumentEndIndex; ++$i) { + $newSecondArgumentTokens[] = clone $tokens[$i]; + $tokens->clearAt($i); + } + + $tokens->insertAt($firstArgumentIndex, clone $tokens[$secondArgumentIndex]); + + // insert above increased the second argument index + ++$secondArgumentIndex; + $tokens->clearAt($secondArgumentIndex); + $tokens->insertAt($secondArgumentIndex, $newSecondArgumentTokens); + } + } + } + + /** + * @return array In the format: startIndex => endIndex + */ + private function getArgumentIndices(Tokens $tokens, int $functionNameIndex): array + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $openParenthesis = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis); + + $indices = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis) as $startIndexCandidate => $endIndex) { + $indices[$tokens->getNextMeaningfulToken($startIndexCandidate - 1)] = $tokens->getPrevMeaningfulToken($endIndex + 1); + } + + return $indices; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php new file mode 100644 index 0000000..4bddcf1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php @@ -0,0 +1,351 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LambdaNotUsedImportFixer extends AbstractFixer +{ + private ArgumentsAnalyzer $argumentsAnalyzer; + + private FunctionsAnalyzer $functionAnalyzer; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Lambda must not import variables it doesn\'t use.', + [new CodeSample("isAllTokenKindsFound([\T_FUNCTION, CT::T_USE_LAMBDA]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->argumentsAnalyzer = new ArgumentsAnalyzer(); + $this->functionAnalyzer = new FunctionsAnalyzer(); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + $lambdaUseIndex = $this->getLambdaUseIndex($tokens, $index); + + if (false !== $lambdaUseIndex) { + $this->fixLambda($tokens, $lambdaUseIndex); + } + } + } + + private function fixLambda(Tokens $tokens, int $lambdaUseIndex): void + { + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($lambdaUseIndex, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->filterArguments($tokens, $arguments); + + if (0 === \count($imports)) { + return; // no imports to remove + } + + $notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex); + $notUsedImportsCount = \count($notUsedImports); + + if (0 === $notUsedImportsCount) { + return; // no not used imports found + } + + if ($notUsedImportsCount === \count($arguments)) { + $this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex); // all imports are not used + + return; + } + + $this->clearImports($tokens, array_reverse($notUsedImports)); + } + + /** + * @param array $imports + * + * @return array + */ + private function findNotUsedLambdaImports(Tokens $tokens, array $imports, int $lambdaUseCloseBraceIndex): array + { + // figure out where the lambda starts ... + $lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); + $curlyBracesLevel = 0; + + for ($index = $lambdaOpenIndex;; ++$index) { // go through the body of the lambda and keep count of the (possible) usages of the imported variables + $token = $tokens[$index]; + + if ($token->equals('{')) { + ++$curlyBracesLevel; + + continue; + } + + if ($token->equals('}')) { + --$curlyBracesLevel; + + if (0 === $curlyBracesLevel) { + break; + } + + continue; + } + + if ($token->isGivenKind(\T_STRING) && 'compact' === strtolower($token->getContent()) && $this->functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return []; // wouldn't touch it with a ten-foot pole + } + + if ($token->isGivenKind([ + CT::T_DYNAMIC_VAR_BRACE_OPEN, + \T_EVAL, + \T_INCLUDE, + \T_INCLUDE_ONCE, + \T_REQUIRE, + \T_REQUIRE_ONCE, + ])) { + return []; + } + + if ($token->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + return []; // "$$a" case + } + } + + if ($token->isGivenKind(\T_VARIABLE)) { + $content = $token->getContent(); + + if (isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + if ($token->isGivenKind(\T_STRING_VARNAME)) { + $content = '$'.$token->getContent(); + + if (isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + if ($token->isClassy()) { // is anonymous class + // check if used as argument in the constructor of the anonymous class + $index = $tokens->getNextTokenOfKind($index, ['(', '{']); + + if ($tokens[$index]->equals('(')) { + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $index, $closeBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + $index = $tokens->getNextTokenOfKind($closeBraceIndex, ['{']); + } + + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($token->isGivenKind(\T_FUNCTION)) { + // check if used as argument + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + // check if used as import + $index = $tokens->getNextTokenOfKind($index, [[CT::T_USE_LAMBDA], '{']); + + if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { + $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $lambdaUseOpenBraceIndex); + $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); + + $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); + + $index = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); + } + + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + } + + return $imports; + } + + /** + * @param array $imports + * @param array $arguments + * + * @return array + */ + private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments): array + { + foreach ($arguments as $start => $end) { + $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); + $content = $info->getName(); + + if (null !== $content && isset($imports[$content])) { + unset($imports[$content]); + + if (0 === \count($imports)) { + return $imports; + } + } + } + + return $imports; + } + + /** + * @return false|int + */ + private function getLambdaUseIndex(Tokens $tokens, int $index) + { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) { + return false; + } + + $lambdaUseIndex = $tokens->getNextMeaningfulToken($index); // we are @ '(' or '&' after this + + if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) { + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + } + + $lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $lambdaUseIndex); // we are @ ')' after this + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + + if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) { + return false; + } + + return $lambdaUseIndex; + } + + /** + * @param array $arguments + * + * @return array + */ + private function filterArguments(Tokens $tokens, array $arguments): array + { + $imports = []; + + foreach ($arguments as $start => $end) { + $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); + $argument = $info->getNameIndex(); + + if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) { + continue; + } + + $argumentCandidate = $tokens[$argument]; + + if ('$this' === $argumentCandidate->getContent()) { + continue; + } + + if ($this->tokensAnalyzer->isSuperGlobal($argument)) { + continue; + } + + $imports[$argumentCandidate->getContent()] = $argument; + } + + return $imports; + } + + /** + * @param array $imports + */ + private function clearImports(Tokens $tokens, array $imports): void + { + foreach ($imports as $removeIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex); + $previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex); + + if ($tokens[$previousRemoveIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex); + } elseif ($tokens[$previousRemoveIndex]->equals('(')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); // next is always ',' here + } + } + } + + /** + * Remove `use` and all imported variables. + */ + private function clearImportsAndUse(Tokens $tokens, int $lambdaUseIndex, int $lambdaUseCloseBraceIndex): void + { + for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) { + if ($tokens[$i]->isComment()) { + continue; + } + + if ($tokens[$i]->isWhitespace()) { + $previousIndex = $tokens->getPrevNonWhitespace($i); + + if ($tokens[$previousIndex]->isComment()) { + continue; + } + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php new file mode 100644 index 0000000..53a86cb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php @@ -0,0 +1,611 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * after_heredoc?: bool, + * attribute_placement?: 'ignore'|'same_line'|'standalone', + * keep_multiple_spaces_after_comma?: bool, + * on_multiline?: 'ensure_fully_multiline'|'ensure_single_line'|'ensure_single_line_for_single_argument'|'ignore', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * after_heredoc: bool, + * attribute_placement: 'ignore'|'same_line'|'standalone', + * keep_multiple_spaces_after_comma: bool, + * on_multiline: 'ensure_fully_multiline'|'ensure_single_line'|'ensure_single_line_for_single_argument'|'ignore', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Kuanhung Chen + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MethodArgumentSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma. Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.', + [ + new CodeSample( + " false], + ), + new CodeSample( + " true], + ), + new CodeSample( + " 'ensure_fully_multiline'], + ), + new CodeSample( + " 'ensure_single_line'], + ), + new CodeSample( + " 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ], + ), + new CodeSample( + " 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => false, + ], + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'ignore', + ], + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'same_line', + ], + ), + new CodeSample( + " 'ensure_fully_multiline', + 'attribute_placement' => 'standalone', + ], + ), + new CodeSample( + " 'ensure_single_line_for_single_argument'], + ), + new CodeSample( + <<<'SAMPLE' + true], + ), + ], + 'This fixer covers rules defined in PSR2 ¶4.4, ¶4.6.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('('); + } + + /** + * {@inheritdoc} + * + * Must run before ArrayIndentationFixer, NoTrailingCommaInSinglelineFixer, StatementIndentationFixer. + * Must run after CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, LambdaNotUsedImportFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer. + */ + public function getPriority(): int + { + return 30; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $expectedTokens = [\T_LIST, \T_FUNCTION, CT::T_USE_LAMBDA, \T_FN, \T_CLASS]; + + $tokenCount = $tokens->count(); + for ($index = 1; $index < $tokenCount; ++$index) { + $token = $tokens[$index]; + + if (!$token->equals('(')) { + continue; + } + + $meaningfulTokenBeforeParenthesis = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if ( + $meaningfulTokenBeforeParenthesis->isKeyword() + && !$meaningfulTokenBeforeParenthesis->isGivenKind($expectedTokens) + ) { + continue; + } + + $isMultiline = $this->fixFunction($tokens, $index); + + if ( + $isMultiline + && \in_array($this->configuration['on_multiline'], ['ensure_fully_multiline', 'ensure_single_line_for_single_argument'], true) + && !$meaningfulTokenBeforeParenthesis->isGivenKind(\T_LIST) + ) { + if ('ensure_single_line_for_single_argument' === $this->configuration['on_multiline']) { + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + if (1 === $argumentsAnalyzer->countArguments($tokens, $index, $endFunctionIndex)) { + $this->ensureSingleLineForParentheses($tokens, $index, $endFunctionIndex); + } else { + $this->ensureFunctionFullyMultiline($tokens, $index); + } + } else { + $this->ensureFunctionFullyMultiline($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('keep_multiple_spaces_after_comma', 'Whether keep multiple spaces after comma.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'on_multiline', + 'Defines how to handle function arguments lists that contain newlines.', + )) + ->setAllowedValues(['ignore', 'ensure_single_line', 'ensure_fully_multiline', 'ensure_single_line_for_single_argument']) + ->setDefault('ensure_fully_multiline') + ->getOption(), + (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + (new FixerOptionBuilder( + 'attribute_placement', + 'Defines how to handle argument attributes when function definition is multiline.', + )) + ->setAllowedValues(['ignore', 'same_line', 'standalone']) + ->setDefault('standalone') + ->getOption(), + ]); + } + + /** + * Fix arguments spacing for given function. + * + * @param Tokens $tokens Tokens to handle + * @param int $startFunctionIndex Start parenthesis position + * + * @return bool whether the function is multiline + */ + private function fixFunction(Tokens $tokens, int $startFunctionIndex): bool + { + $isMultiline = false; + + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startFunctionIndex); + $firstWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $startFunctionIndex, $endFunctionIndex); + $lastWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $endFunctionIndex, $startFunctionIndex); + + foreach ([$firstWhitespaceIndex, $lastWhitespaceIndex] as $index) { + if (null === $index || !Preg::match('/\R/', $tokens[$index]->getContent())) { + continue; + } + + if ('ensure_single_line' !== $this->configuration['on_multiline']) { + $isMultiline = true; + + continue; + } + + $newLinesRemoved = $this->ensureSingleLine($tokens, $index); + + if (!$newLinesRemoved) { + $isMultiline = true; + } + } + + for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { + $token = $tokens[$index]; + + if ($token->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + continue; + } + + if ($token->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($token->equals(',')) { + $this->fixSpace($tokens, $index); + if (!$isMultiline && $this->isNewline($tokens[$index + 1])) { + $isMultiline = true; + } + } + } + + return $isMultiline; + } + + private function findWhitespaceIndexAfterParenthesis(Tokens $tokens, int $startParenthesisIndex, int $endParenthesisIndex): ?int + { + $direction = $endParenthesisIndex > $startParenthesisIndex ? 1 : -1; + $startIndex = $startParenthesisIndex + $direction; + $endIndex = $endParenthesisIndex - $direction; + + for ($index = $startIndex; $index !== $endIndex; $index += $direction) { + $token = $tokens[$index]; + + if ($token->isWhitespace()) { + return $index; + } + + if (!$token->isComment()) { + break; + } + } + + return null; + } + + /** + * @return bool Whether newlines were removed from the whitespace token + */ + private function ensureSingleLine(Tokens $tokens, int $index): bool + { + $previousToken = $tokens[$index - 1]; + + if ($previousToken->isComment() && !str_starts_with($previousToken->getContent(), '/*')) { + return false; + } + + $content = Preg::replace('/\R\h*/', '', $tokens[$index]->getContent()); + + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + + return true; + } + + private function ensureFunctionFullyMultiline(Tokens $tokens, int $startFunctionIndex): void + { + // find out what the indentation is + $searchIndex = $startFunctionIndex; + do { + $prevWhitespaceTokenIndex = $tokens->getPrevTokenOfKind( + $searchIndex, + [[\T_ENCAPSED_AND_WHITESPACE], [\T_INLINE_HTML], [\T_WHITESPACE]], + ); + + $searchIndex = $prevWhitespaceTokenIndex; + } while (null !== $prevWhitespaceTokenIndex + && !str_contains($tokens[$prevWhitespaceTokenIndex]->getContent(), "\n") + ); + + if (null === $prevWhitespaceTokenIndex) { + $existingIndentation = ''; + } elseif (!$tokens[$prevWhitespaceTokenIndex]->isGivenKind(\T_WHITESPACE)) { + return; + } else { + $existingIndentation = $tokens[$prevWhitespaceTokenIndex]->getContent(); + $lastLineIndex = strrpos($existingIndentation, "\n"); + $existingIndentation = false === $lastLineIndex + ? $existingIndentation + : substr($existingIndentation, $lastLineIndex + 1); + } + + $indentation = $existingIndentation.$this->whitespacesConfig->getIndent(); + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startFunctionIndex); + + $wasWhitespaceBeforeEndFunctionAddedAsNewToken = $tokens->ensureWhitespaceAtIndex( + $tokens[$endFunctionIndex - 1]->isWhitespace() ? $endFunctionIndex - 1 : $endFunctionIndex, + 0, + $this->whitespacesConfig->getLineEnding().$existingIndentation, + ); + + if ($wasWhitespaceBeforeEndFunctionAddedAsNewToken) { + ++$endFunctionIndex; + } + + for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { + $token = $tokens[$index]; + + // skip nested method calls and arrays + if ($token->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + // skip nested arrays + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + continue; + } + + if ($token->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($tokens[$tokens->getNextMeaningfulToken($index)]->equals(')')) { + continue; + } + + if ($token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + if ('standalone' === $this->configuration['attribute_placement']) { + $this->fixNewline($tokens, $index, $indentation); + } elseif ('same_line' === $this->configuration['attribute_placement']) { + $this->ensureSingleLine($tokens, $index + 1); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ($token->equals(',')) { + $this->fixNewline($tokens, $index, $indentation); + } + } + + $this->fixNewline($tokens, $startFunctionIndex, $indentation, false); + } + + /** + * Method to insert newline after comma, attribute or opening parenthesis. + * + * @param int $index index of a comma + * @param string $indentation the indentation that should be used + * @param bool $override whether to override the existing character or not + */ + private function fixNewline(Tokens $tokens, int $index, string $indentation, bool $override = true): void + { + if ($tokens[$index + 1]->isComment()) { + return; + } + + if ($tokens[$index + 2]->isComment()) { + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index + 2); + if (!$this->isNewline($tokens[$nextMeaningfulTokenIndex - 1])) { + if ($tokens[$nextMeaningfulTokenIndex - 1]->isWhitespace()) { + $tokens->clearAt($nextMeaningfulTokenIndex - 1); + } + + $tokens->ensureWhitespaceAtIndex($nextMeaningfulTokenIndex, 0, $this->whitespacesConfig->getLineEnding().$indentation); + } + + return; + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextMeaningfulTokenIndex]->equals(')')) { + return; + } + + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $this->whitespacesConfig->getLineEnding().$indentation); + } + + /** + * Method to insert space after comma and remove space before comma. + */ + private function fixSpace(Tokens $tokens, int $index): void + { + // remove space before comma if exist + if ($tokens[$index - 1]->isWhitespace()) { + $prevIndex = $tokens->getPrevNonWhitespace($index - 1); + + if ( + !$tokens[$prevIndex]->equals(',') && !$tokens[$prevIndex]->isComment() + && (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC)) + ) { + $tokens->clearAt($index - 1); + } + } + + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex]; + + // Two cases for fix space after comma (exclude multiline comments) + // 1) multiple spaces after comma + // 2) no space after comma + if ($nextToken->isWhitespace()) { + $newContent = $nextToken->getContent(); + + if ('ensure_single_line' === $this->configuration['on_multiline']) { + $newContent = Preg::replace('/\R/', '', $newContent); + } + + if ( + (false === $this->configuration['keep_multiple_spaces_after_comma'] || Preg::match('/\R/', $newContent)) + && !$this->isCommentLastLineToken($tokens, $index + 2) + ) { + $newContent = ltrim($newContent, " \t"); + } + + $tokens[$nextIndex] = new Token([\T_WHITESPACE, '' === $newContent ? ' ' : $newContent]); + + return; + } + + if (!$this->isCommentLastLineToken($tokens, $index + 1)) { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + } + + /** + * Check if last item of current line is a comment. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function isCommentLastLineToken(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) { + return false; + } + + $content = $tokens[$index + 1]->getContent(); + + return $content !== ltrim($content, "\r\n"); + } + + /** + * Checks if token is new line. + */ + private function isNewline(Token $token): bool + { + return $token->isWhitespace() && str_contains($token->getContent(), "\n"); + } + + /** + * Check if the argument content should not be collapsed — either spans multiple lines + * outside nested blocks and boundary whitespace, or contains comments or attributes. + */ + private function argumentContentIsMultiline(Tokens $tokens, int $openParenthesis, int $closeParenthesis): bool + { + for ($index = $openParenthesis + 1; $index < $closeParenthesis; ++$index) { + if ($tokens[$index]->isComment()) { + return true; + } + + if ($index === $openParenthesis + 1 || $index === $closeParenthesis - 1) { + continue; + } + + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + continue; + } + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($this->isNewline($tokens[$index])) { + return true; + } + } + + return false; + } + + /** + * Collapse a multiline single-argument call/declaration to a single line. + */ + private function ensureSingleLineForParentheses(Tokens $tokens, int $openParenthesis, int $closeParenthesis): void + { + if ($this->argumentContentIsMultiline($tokens, $openParenthesis, $closeParenthesis)) { + return; + } + + for ($index = $closeParenthesis - 1; $index > $openParenthesis; --$index) { + if ($tokens[$index]->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_ARRAY_BRACKET_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + continue; + } + + if ($tokens[$index]->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($tokens[$index]->isWhitespace()) { + $previousToken = $tokens[$index - 1]; + + if ($previousToken->isComment() && !str_starts_with($previousToken->getContent(), '/*')) { + continue; + } + + $content = Preg::replace('/\R\h*/', '', $tokens[$index]->getContent()); + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MultilinePromotedPropertiesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MultilinePromotedPropertiesFixer.php new file mode 100644 index 0000000..e451de4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MultilinePromotedPropertiesFixer.php @@ -0,0 +1,287 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _InputConfig array{keep_blank_lines?: bool, minimum_number_of_parameters?: int} + * @phpstan-type _Config array{keep_blank_lines: bool, minimum_number_of_parameters: int} + * @phpstan-type _AutogeneratedInputConfiguration array{ + * keep_blank_lines?: bool, + * minimum_number_of_parameters?: int, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * keep_blank_lines: bool, + * minimum_number_of_parameters: int, + * } + * @phpstan-type _ConstructorAnalysis array{ + * index?: int, + * parameter_names: list, + * promotable_parameters: array, + * constructor_index?: int, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @TODO align on default configuration and remove experimental flag - https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/8718 + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MultilinePromotedPropertiesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, ExperimentalFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Promoted properties must be on separate lines.', + [ + new VersionSpecificCodeSample( + <<<'PHP' + 3], + ), + new VersionSpecificCodeSample( + <<<'PHP' + 3], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesPositionFixer, TrailingCommaInMultilineFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + ]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('keep_blank_lines', 'Whether to keep blank lines between properties.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('minimum_number_of_parameters', 'Minimum number of parameters in the constructor to fix.')) + ->setAllowedTypes(['int']) + ->setDefault(1) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { + if ('method' !== $element['type']) { + continue; + } + + $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + + if ($this->shouldBeMultiline($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { + $this->makeMultiline($tokens, $openParenthesisIndex, $closeParenthesisIndex); + } elseif ($this->shouldBeSingleline($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { + $this->makeSingleline($tokens, $openParenthesisIndex, $closeParenthesisIndex); + } + } + } + + private function shouldBeMultiline(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool + { + $promotedParameterFound = false; + $minimumNumberOfParameters = 0; + for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + ++$minimumNumberOfParameters; + } + if ( + $tokens[$index]->isGivenKind([ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + ]) + ) { + $promotedParameterFound = true; + } + } + + return $promotedParameterFound && $minimumNumberOfParameters >= $this->configuration['minimum_number_of_parameters']; + } + + private function shouldBeSingleline(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool + { + $promotedParameterFound = false; + $parameterCount = 0; + $isMultiline = false; + + for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + ++$parameterCount; + } + + if ( + $tokens[$index]->isGivenKind([ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + ]) + ) { + $promotedParameterFound = true; + } + + if ($tokens[$index]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT, \T_ATTRIBUTE])) { + return false; + } + + if ( + $tokens[$index]->isWhitespace() + && str_contains($tokens[$index]->getContent(), "\n") + ) { + $isMultiline = true; + } + } + + return $promotedParameterFound && $isMultiline && $parameterCount < $this->configuration['minimum_number_of_parameters']; + } + + private function makeSingleline(Tokens $tokens, int $openParenthesis, int $closeParenthesis): void + { + for ($index = $closeParenthesis - 1; $index > $openParenthesis; --$index) { + if (!$tokens[$index]->isWhitespace()) { + continue; + } + + if (!str_contains($tokens[$index]->getContent(), "\n")) { + continue; + } + + if ($index === $openParenthesis + 1 || $index === $closeParenthesis - 1) { + $tokens->clearAt($index); + } else { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + } + } + + private function makeMultiline(Tokens $tokens, int $openParenthesis, int $closeParenthesis): void + { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $openParenthesis); + + $tokens->ensureWhitespaceAtIndex( + $closeParenthesis - 1, + 1, + $this->whitespacesConfig->getLineEnding().$indent, + ); + + $index = $tokens->getPrevMeaningfulToken($closeParenthesis); + if (!$tokens[$index]->equals(',')) { + $index = $closeParenthesis; + } + + while ($index > $openParenthesis) { + $index = $tokens->getPrevMeaningfulToken($index); + \assert(\is_int($index)); + + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null !== $blockType && !$blockType['isStart']) { + $index = $tokens->findBlockStart($blockType['type'], $index); + + continue; + } + + if (!$tokens[$index]->equalsAny(['(', ','])) { + continue; + } + + $this->fixParameter($tokens, $index + 1, $indent); + } + } + + private function fixParameter(Tokens $tokens, int $index, string $indent): void + { + if ($this->configuration['keep_blank_lines'] && $tokens[$index]->isWhitespace() && str_contains($tokens[$index]->getContent(), "\n")) { + return; + } + + $tokens->ensureWhitespaceAtIndex( + $index, + 0, + $this->whitespacesConfig->getLineEnding().$indent.$this->whitespacesConfig->getIndent(), + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php new file mode 100644 index 0000000..ee870a9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php @@ -0,0 +1,436 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * exclude?: list, + * include?: list, + * scope?: 'all'|'namespaced', + * strict?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * exclude: list, + * include: list, + * scope: 'all'|'namespaced', + * strict: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const SET_ALL = '@all'; + + /** + * Subset of SET_INTERNAL. + * + * Change function call to functions known to be optimized by the Zend engine. + * For details: + * - @see https://github.com/php/php-src/blob/php-7.2.6/Zend/zend_compile.c "zend_try_compile_special_func" + * - @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + * + * @internal + */ + public const SET_COMPILER_OPTIMIZED = '@compiler_optimized'; + + /** + * @internal + */ + public const SET_INTERNAL = '@internal'; + + /** + * @var callable + */ + private $functionFilter; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add leading `\` before function invocation to speed up resolving.', + [ + new CodeSample( + <<<'PHP' + [ + 'json_encode', + ], + ], + ), + new CodeSample( + <<<'PHP' + 'all'], + ), + new CodeSample( + <<<'PHP' + 'namespaced'], + ), + new CodeSample( + <<<'PHP' + ['myGlobalFunction']], + ), + new CodeSample( + <<<'PHP' + [self::SET_ALL]], + ), + new CodeSample( + <<<'PHP' + [self::SET_INTERNAL]], + ), + new CodeSample( + <<<'PHP' + [self::SET_COMPILER_OPTIMIZED]], + ), + ], + null, + 'Risky when any of the functions are overridden.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + * Must run after BacktickToShellExecFixer, MbStrFunctionsFixer, RegularCallableCallFixer, StrictParamFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->functionFilter = $this->getFunctionFilter(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('all' === $this->configuration['scope']) { + $this->fixFunctionCalls($tokens, $this->functionFilter, 0, \count($tokens) - 1, false); + + return; + } + + $namespaces = $tokens->getNamespaceDeclarations(); + + // 'scope' is 'namespaced' here + foreach (array_reverse($namespaces) as $namespace) { + $this->fixFunctionCalls($tokens, $this->functionFilter, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex(), $namespace->isGlobalNamespace()); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('exclude', 'List of functions to ignore.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName) { + if ('' === trim($functionName) || trim($functionName) !== $functionName) { + throw new InvalidOptionsException(\sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($functionName), + )); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('include', 'List of function names or sets to fix. Defined sets are `@internal` (all native functions), `@all` (all global functions) and `@compiler_optimized` (functions that are specially optimized by Zend).')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $functionName) { + if ('' === trim($functionName) || trim($functionName) !== $functionName) { + throw new InvalidOptionsException(\sprintf( + 'Each element must be a non-empty, trimmed string, got "%s" instead.', + get_debug_type($functionName), + )); + } + + $sets = [ + self::SET_ALL, + self::SET_INTERNAL, + self::SET_COMPILER_OPTIMIZED, + ]; + + if (str_starts_with($functionName, '@') && !\in_array($functionName, $sets, true)) { + throw new InvalidOptionsException(\sprintf('Unknown set "%s", known sets are %s.', $functionName, Utils::naturalLanguageJoin($sets))); + } + } + + return true; + }]) + ->setDefault([self::SET_COMPILER_OPTIMIZED]) + ->getOption(), + (new FixerOptionBuilder('scope', 'Only fix function calls that are made within a namespace or fix all.')) + ->setAllowedValues(['all', 'namespaced']) + ->setDefault('all') + ->getOption(), + (new FixerOptionBuilder('strict', 'Whether leading `\` of function call not meant to have it should be removed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + private function fixFunctionCalls(Tokens $tokens, callable $functionFilter, int $start, int $end, bool $tryToRemove): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + $tokensToInsert = []; + for ($index = $start; $index < $end; ++$index) { + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$functionFilter($tokens[$index]->getContent()) || $tryToRemove) { + if (false === $this->configuration['strict']) { + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + + continue; + } + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; // do not bother if previous token is already namespace separator + } + + $tokensToInsert[$index] = new Token([\T_NS_SEPARATOR, '\\']); + } + + $tokens->insertSlices($tokensToInsert); + } + + private function getFunctionFilter(): callable + { + $exclude = $this->normalizeFunctionNames($this->configuration['exclude']); + + if (\in_array(self::SET_ALL, $this->configuration['include'], true)) { + if (\count($exclude) > 0) { + return static fn (string $functionName): bool => !isset($exclude[strtolower($functionName)]); + } + + return static fn (): bool => true; + } + + $include = []; + + if (\in_array(self::SET_INTERNAL, $this->configuration['include'], true)) { + $include = $this->getAllInternalFunctionsNormalized(); + } elseif (\in_array(self::SET_COMPILER_OPTIMIZED, $this->configuration['include'], true)) { + $include = $this->getAllCompilerOptimizedFunctionsNormalized(); // if `@internal` is set all compiler optimized function are already loaded + } + + foreach ($this->configuration['include'] as $additional) { + if (!str_starts_with($additional, '@')) { + $include[strtolower($additional)] = true; + } + } + + if (\count($exclude) > 0) { + return static fn (string $functionName): bool => isset($include[strtolower($functionName)]) && !isset($exclude[strtolower($functionName)]); + } + + return static fn (string $functionName): bool => isset($include[strtolower($functionName)]); + } + + /** + * @return array normalized function names of which the PHP compiler optimizes + */ + private function getAllCompilerOptimizedFunctionsNormalized(): array + { + return $this->normalizeFunctionNames([ + // @see https://github.com/php/php-src/blob/PHP-7.4/Zend/zend_compile.c "zend_try_compile_special_func" + 'array_key_exists', + 'array_slice', + 'assert', + 'boolval', + 'call_user_func', + 'call_user_func_array', + 'chr', + 'count', + 'defined', + 'doubleval', + 'floatval', + 'func_get_args', + 'func_num_args', + 'get_called_class', + 'get_class', + 'gettype', + 'in_array', + 'intval', + 'is_array', + 'is_bool', + 'is_double', + 'is_float', + 'is_int', + 'is_integer', + 'is_long', + 'is_null', + 'is_object', + 'is_real', + 'is_resource', + 'is_scalar', + 'is_string', + 'ord', + 'sizeof', + 'sprintf', + 'strlen', + 'strval', + // @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + // @see https://github.com/php/php-src/blob/PHP-8.1.2/Zend/Optimizer/block_pass.c + // @see https://github.com/php/php-src/blob/php-8.1.3/Zend/Optimizer/zend_optimizer.c + 'constant', + 'define', + 'dirname', + 'extension_loaded', + 'function_exists', + 'is_callable', + 'ini_get', + ]); + } + + /** + * @return array normalized function names of all internal defined functions + */ + private function getAllInternalFunctionsNormalized(): array + { + return $this->normalizeFunctionNames(get_defined_functions()['internal']); + } + + /** + * @param list $functionNames + * + * @return array all function names lower cased + */ + private function normalizeFunctionNames(array $functionNames): array + { + $result = []; + + foreach ($functionNames as $functionName) { + $result[strtolower($functionName)] = true; + } + + return $result; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php new file mode 100644 index 0000000..565cf0a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.6. + * + * @author Varga Bence + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSpacesAfterFunctionNameFixer extends AbstractFixer +{ + /** + * Token kinds which can work as function calls. + */ + private const FUNCTIONY_TOKEN_KINDS = [ + \T_ARRAY, + \T_ECHO, + \T_EMPTY, + \T_EVAL, + \T_EXIT, + \T_INCLUDE, + \T_INCLUDE_ONCE, + \T_ISSET, + \T_LIST, + \T_PRINT, + \T_REQUIRE, + \T_REQUIRE_ONCE, + \T_UNSET, + \T_VARIABLE, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.', + [new CodeSample("isAnyTokenKindsFound([\T_STRING, ...self::FUNCTIONY_TOKEN_KINDS]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + // looking for start brace + if (!$token->equals('(')) { + continue; + } + + // last non-whitespace token, can never be `null` always at least PHP open tag before it + $lastTokenIndex = $tokens->getPrevNonWhitespace($index); + + // check for ternary operator + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex); + if ( + null !== $nextNonWhiteSpace + && !$tokens[$nextNonWhiteSpace]->equals(';') + && $tokens[$lastTokenIndex]->isGivenKind([ + \T_ECHO, + \T_PRINT, + \T_INCLUDE, + \T_INCLUDE_ONCE, + \T_REQUIRE, + \T_REQUIRE_ONCE, + ]) + ) { + continue; + } + + // check if it is a function call + if ($tokens[$lastTokenIndex]->isGivenKind(self::FUNCTIONY_TOKEN_KINDS)) { + $this->fixFunctionCall($tokens, $index); + } elseif ($tokens[$lastTokenIndex]->isGivenKind(\T_STRING)) { // for real function calls or definitions + $possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex); + if (!$tokens[$possibleDefinitionIndex]->isGivenKind(\T_FUNCTION)) { + $this->fixFunctionCall($tokens, $index); + } + } elseif ($tokens[$lastTokenIndex]->equalsAny([ + ')', + ']', + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + ])) { + $block = Tokens::detectBlockType($tokens[$lastTokenIndex]); + if ( + Tokens::BLOCK_TYPE_INDEX_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] + || Tokens::BLOCK_TYPE_INDEX_BRACKET === $block['type'] + || Tokens::BLOCK_TYPE_PARENTHESIS === $block['type'] + ) { + $this->fixFunctionCall($tokens, $index); + } + } + } + } + + /** + * Fixes whitespaces around braces of a function(y) call. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function fixFunctionCall(Tokens $tokens, int $index): void + { + // remove space before opening brace + if ($tokens[$index - 1]->isWhitespace()) { + $tokens->clearAt($index - 1); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php new file mode 100644 index 0000000..e66ac38 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingCommaInSinglelineFunctionCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'When making a method or function call on a single line there MUST NOT be a trailing comma after the last argument.', + [new CodeSample("proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['arguments', 'array_destructuring']]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php new file mode 100644 index 0000000..78208fc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php @@ -0,0 +1,158 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Mark Scherer + * @author Lucas Manzke + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnreachableDefaultArgumentValueFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'In function arguments there must not be arguments with default values before non-default ones.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionKinds = [\T_FUNCTION, \T_FN]; + + for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) { + if (!$tokens[$i]->isGivenKind($functionKinds)) { + continue; + } + + $this->fixFunctionDefinition($tokens, $i); + } + } + + private function fixFunctionDefinition(Tokens $tokens, int $startIndex): void + { + $removeDefaultArgument = false; + + foreach (array_reverse((new FunctionsAnalyzer())->getFunctionArguments($tokens, $startIndex)) as $argumentAnalysis) { + $prevVariableIndex = $tokens->getPrevMeaningfulToken($argumentAnalysis->getNameIndex()); + if ($tokens[$prevVariableIndex]->isGivenKind(\T_ELLIPSIS)) { + continue; + } + + if (null === $argumentAnalysis->getDefault()) { + $removeDefaultArgument = true; + + continue; + } + + if (!$removeDefaultArgument) { + continue; + } + + if ( + 'null' === strtolower($argumentAnalysis->getDefault()) + && $argumentAnalysis->hasTypeAnalysis() + && !$argumentAnalysis->getTypeAnalysis()->isNullable() + ) { + continue; + } + + $this->removeDefaultValue( + $tokens, + $argumentAnalysis->getNameIndex(), + $this->getDefaultValueEnd($tokens, $argumentAnalysis->getNameIndex()), + ); + } + } + + private function removeDefaultValue(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $tokens->getNextMeaningfulToken($startIndex); $i <= $endIndex;) { + $this->clearWhitespacesBeforeIndex($tokens, $i); + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getNextMeaningfulToken($i); + } + } + + private function getDefaultValueEnd(Tokens $tokens, int $index): int + { + while (null !== $index = $tokens->getNextMeaningfulToken($index)) { + if ($tokens[$index]->equalsAny([',', [CT::T_PROPERTY_HOOK_BRACE_OPEN]])) { + break; + } + + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + } + } + + return $tokens->getPrevMeaningfulToken($index); + } + + private function clearWhitespacesBeforeIndex(Tokens $tokens, int $index): void + { + $prevIndex = $tokens->getNonEmptySibling($index, -1); + if (!$tokens[$prevIndex]->isWhitespace()) { + return; + } + + $prevNonWhiteIndex = $tokens->getPrevNonWhitespace($prevIndex); + if (null === $prevNonWhiteIndex || !$tokens[$prevNonWhiteIndex]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessPrintfFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessPrintfFixer.php new file mode 100644 index 0000000..8b82892 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessPrintfFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author John Paul E. Balandan, CPA + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessPrintfFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no `printf` calls with only the first argument.', + [ + new CodeSample( + "isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before EchoTagSyntaxFixer, NoExtraBlankLinesFixer, NoMixedEchoPrintFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $printfIndices = []; + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + + if ('printf' !== strtolower($tokens[$index]->getContent())) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + + if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind([\T_ELLIPSIS, CT::T_FIRST_CLASS_CALLABLE])) { + continue; + } + + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + + if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + + if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + + $printfIndices[] = $index; + } + + if ([] === $printfIndices) { + return; + } + + $tokens->insertSlices(array_combine( + $printfIndices, + array_fill(0, \count($printfIndices), [new Token([\T_PRINT, 'print']), new Token([\T_WHITESPACE, ' '])]), + )); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php new file mode 100644 index 0000000..075922f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php @@ -0,0 +1,112 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessSprintfFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no `sprintf` calls with only the first argument.', + [ + new CodeSample( + "isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionCasingFixer, NoEmptyStatementFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + */ + public function getPriority(): int + { + return 42; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + + if ('sprintf' !== strtolower($tokens[$index]->getContent())) { + continue; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + + if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(\T_ELLIPSIS)) { + continue; + } + + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + + if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + + if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php new file mode 100644 index 0000000..d5bb4e2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php @@ -0,0 +1,248 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * use_nullable_type_declaration?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * use_nullable_type_declaration: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author HypeMC + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullableTypeDeclarationForDefaultNullValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + private const CONSTRUCTOR_PROPERTY_MODIFIERS = [ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + FCT::T_PUBLIC_SET, + FCT::T_PROTECTED_SET, + FCT::T_PRIVATE_SET, + FCT::T_READONLY, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds or removes `?` before single type declarations or `|null` at the end of union types when parameters have a default `null` value.', + [ + new CodeSample( + " false], + ), + new VersionSpecificCodeSample( + " false], + ), + new VersionSpecificCodeSample( + " false], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_VARIABLE) && $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnreachableDefaultArgumentValueFixer, NullableTypeDeclarationFixer, OrderedTypesFixer. + */ + public function getPriority(): int + { + return 3; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_nullable_type_declaration', 'Whether to add or remove `?` or `|null` to parameters with a default `null` value.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->setDeprecationMessage('Behaviour will follow default one.') // @TODO remove the option on next major 4.0 + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $tokenKinds = [\T_FUNCTION, \T_FN]; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($tokenKinds)) { + continue; + } + + $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); + $this->fixFunctionParameters($tokens, $arguments); + } + } + + /** + * @param array $arguments + */ + private function fixFunctionParameters(Tokens $tokens, array $arguments): void + { + foreach (array_reverse($arguments) as $argumentInfo) { + if ( + // Skip, if the parameter + // - doesn't have a type declaration + !$argumentInfo->hasTypeAnalysis() + // - has a mixed or standalone null type + || \in_array(strtolower($argumentInfo->getTypeAnalysis()->getName()), ['mixed', 'null'], true) + // - a default value is not null we can continue + || !$argumentInfo->hasDefault() || 'null' !== strtolower($argumentInfo->getDefault()) + ) { + continue; + } + + $argumentTypeInfo = $argumentInfo->getTypeAnalysis(); + + if (\PHP_VERSION_ID >= 8_00_00 && false === $this->configuration['use_nullable_type_declaration']) { + $visibility = $tokens[$tokens->getPrevMeaningfulToken($argumentTypeInfo->getStartIndex())]; + + if ($visibility->isGivenKind(self::CONSTRUCTOR_PROPERTY_MODIFIERS)) { + continue; + } + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + if (str_contains($typeAnalysisName, '|') || str_contains($typeAnalysisName, '&')) { + $this->fixUnionTypeParameter($tokens, $argumentTypeInfo); + } else { + $this->fixSingleTypeParameter($tokens, $argumentTypeInfo); + } + } + } + + private function fixSingleTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void + { + if (true === $this->configuration['use_nullable_type_declaration']) { + if (!$argumentTypeInfo->isNullable()) { + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_NULLABLE_TYPE, '?'])); + } + } elseif ($argumentTypeInfo->isNullable()) { + $tokens->removeTrailingWhitespace($startIndex = $argumentTypeInfo->getStartIndex()); + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + } + } + + private function fixUnionTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void + { + if (true === $this->configuration['use_nullable_type_declaration']) { + if ($argumentTypeInfo->isNullable()) { + return; + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + $endIndex = $argumentTypeInfo->getEndIndex(); + + if (str_contains($typeAnalysisName, '&') && !str_contains($typeAnalysisName, '|')) { + $endIndex += 2; + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $tokens->insertAt($endIndex, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'])); + } + + $tokens->insertAt($endIndex + 1, [ + new Token([CT::T_TYPE_ALTERNATION, '|']), + new Token([\T_STRING, 'null']), + ]); + } elseif ($argumentTypeInfo->isNullable()) { + $startIndex = $argumentTypeInfo->getStartIndex(); + + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[\T_STRING, 'null']], false); + + if ($index === $startIndex) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } else { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + $typeAnalysisName = $argumentTypeInfo->getName(); + + if (str_contains($typeAnalysisName, '&') && 1 === substr_count($typeAnalysisName, '|')) { + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN]]); + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + $index = $tokens->getPrevTokenOfKind($argumentTypeInfo->getEndIndex() + 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]]); + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php new file mode 100644 index 0000000..dc686d7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php @@ -0,0 +1,266 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * scalar_types?: bool, + * types_map?: array, + * union_types?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * scalar_types: bool, + * types_map: array, + * union_types: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenArray from Token + * + * @author Jan Gantzert + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocToParamTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface +{ + private const TYPE_CHECK_TEMPLATE = ' + */ + private const EXCLUDE_FUNC_NAMES = [ + [\T_STRING, '__clone'], + [\T_STRING, '__destruct'], + ]; + + /** + * @var array + */ + private const SKIPPED_TYPES = [ + 'resource' => true, + 'static' => true, + 'void' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Takes `@param` annotations of non-mixed types and adjusts accordingly the function signature.', + [ + new CodeSample( + <<<'PHP' + false], + ), + new CodeSample( + <<<'PHP' + false], + ), + ], + null, + 'The `@param` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. Manual actions are required if inherited signatures are not properly documented.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 8; + } + + protected function isSkippedType(string $type): bool + { + return isset(self::SKIPPED_TYPES[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensToInsert = []; + $typesToExclude = []; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); + + continue; + } + + if (!$token->isGivenKind([\T_FUNCTION, \T_FN])) { + continue; + } + + $funcName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$funcName]->equalsAny(self::EXCLUDE_FUNC_NAMES, false)) { + continue; + } + + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + + if (null === $docCommentIndex) { + continue; + } + + foreach ($this->getAnnotationsFromDocComment('param', $tokens, $docCommentIndex) as $paramTypeAnnotation) { + $typesExpression = $paramTypeAnnotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, false); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, false); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $typeInfo) { + $paramType = $typeInfo['commonType']; + $isNullable = $typeInfo['isNullable']; + } else { // null !== $unionTypes, because of previous 2 ifs + $paramType = $unionTypes; + $isNullable = false; + } + + if (\in_array($paramType, $typesToExclude, true)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $variableIndex = $this->findCorrectVariable($tokens, $startIndex, $paramTypeAnnotation); + + if (null === $variableIndex) { + continue; + } + + $byRefIndex = $tokens->getPrevMeaningfulToken($variableIndex); + \assert(\is_int($byRefIndex)); + + if ($tokens[$byRefIndex]->equals('&')) { + $variableIndex = $byRefIndex; + } + + if ($this->hasParamTypeHint($tokens, $variableIndex)) { + continue; + } + + if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $paramType))) { + continue; + } + + $tokensToInsert[$variableIndex] = array_merge( + $this->createTypeDeclarationTokens($paramType, $isNullable), + [new Token([\T_WHITESPACE, ' '])], + ); + } + } + + $tokens->insertSlices($tokensToInsert); + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 4); + $typeTokens->clearRange(\count($typeTokens) - 6, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + private function findCorrectVariable(Tokens $tokens, int $startIndex, Annotation $paramTypeAnnotation): ?int + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startIndex); + + for ($index = $startIndex + 1; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + continue; + } + + $variableName = $tokens[$index]->getContent(); + + if ($paramTypeAnnotation->getVariableName() === $variableName) { + return $index; + } + } + + return null; + } + + /** + * Determine whether the function already has a param type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasParamTypeHint(Tokens $tokens, int $index): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + return !$tokens[$prevIndex]->equalsAny([',', '(']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php new file mode 100644 index 0000000..9d18220 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php @@ -0,0 +1,326 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-import-type _CommonTypeInfo from AbstractPhpdocToTypeDeclarationFixer + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * scalar_types?: bool, + * types_map?: array, + * union_types?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * scalar_types: bool, + * types_map: array, + * union_types: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocToPropertyTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface +{ + private const TYPE_CHECK_TEMPLATE = ' + */ + private array $skippedTypes = [ + 'resource' => true, + 'null' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Takes `@var` annotation of non-mixed types and adjusts accordingly the property signature..', + [ + new CodeSample( + <<<'PHP' + false], + ), + new CodeSample( + <<<'PHP' + false], + ), + ], + null, + 'The `@var` annotation is mandatory for the fixer to make changes, signatures of properties without it (no docblock) will not be fixed. Manual actions might be required for newly typed properties that are read before initialization.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 8; + } + + protected function isSkippedType(string $type): bool + { + return isset($this->skippedTypes[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensToInsert = []; + $typesToExclude = []; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); + + continue; + } + if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { + $tokensToInsert += $this->fixClass($tokens, $index, $typesToExclude); + } + } + + $tokens->insertSlices($tokensToInsert); + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 8); + $typeTokens->clearRange(\count($typeTokens) - 5, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + /** + * @param list $typesToExclude + * + * @return array> + */ + private function fixClass(Tokens $tokens, int $index, array $typesToExclude): array + { + $tokensToInsert = []; + + $index = $tokens->getNextTokenOfKind($index, ['{']); + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + for (; $index < $classEndIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + } + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $docCommentIndex = $index; + $propertyIndices = $this->findNextUntypedPropertiesDeclaration($tokens, $docCommentIndex); + + if ([] === $propertyIndices) { + continue; + } + + $typeInfo = $this->resolveApplicableType( + $propertyIndices, + $this->getAnnotationsFromDocComment('var', $tokens, $docCommentIndex), + ); + + if (null === $typeInfo) { + continue; + } + + $propertyType = $typeInfo['commonType']; + $isNullable = $typeInfo['isNullable']; + + if (\in_array($propertyType, ['callable', 'never', 'void'], true)) { + continue; + } + + if (\in_array($propertyType, $typesToExclude, true)) { + continue; + } + + if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $propertyType))) { + continue; + } + + $newTokens = array_merge( + $this->createTypeDeclarationTokens($propertyType, $isNullable), + [new Token([\T_WHITESPACE, ' '])], + ); + + $tokensToInsert[current($propertyIndices)] = $newTokens; + + $index = max($propertyIndices) + 1; + } + + return $tokensToInsert; + } + + /** + * @return array + */ + private function findNextUntypedPropertiesDeclaration(Tokens $tokens, int $index): array + { + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind([ + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_STATIC, + \T_VAR, + ])); + + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + return []; + } + + $properties = []; + + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + $properties[$tokens[$index]->getContent()] = $index; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return $properties; + } + + /** + * @param array $propertyIndices + * @param list $annotations + * + * @return ?_CommonTypeInfo + */ + private function resolveApplicableType(array $propertyIndices, array $annotations): ?array + { + $propertyTypes = []; + + foreach ($annotations as $annotation) { + $propertyName = $annotation->getVariableName(); + + if (null === $propertyName) { + if (1 !== \count($propertyIndices)) { + continue; + } + + $propertyName = array_key_first($propertyIndices); + } + + if (!isset($propertyIndices[$propertyName])) { + continue; + } + + $typesExpression = $annotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, false); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, false); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $unionTypes) { + $typeInfo = ['commonType' => $unionTypes, 'isNullable' => false]; + } + + if (\array_key_exists($propertyName, $propertyTypes) && $typeInfo !== $propertyTypes[$propertyName]) { + return null; + } + + $propertyTypes[$propertyName] = $typeInfo; + } + + if (\count($propertyTypes) !== \count($propertyIndices)) { + return null; + } + + $type = array_shift($propertyTypes); + + foreach ($propertyTypes as $propertyType) { + if ($propertyType !== $type) { + return null; + } + } + + return $type; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php new file mode 100644 index 0000000..8c60907 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php @@ -0,0 +1,269 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * scalar_types?: bool, + * types_map?: array, + * union_types?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * scalar_types: bool, + * types_map: array, + * union_types: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenArray from Token + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocToReturnTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface +{ + private const TYPE_CHECK_TEMPLATE = ' + */ + private array $excludeFuncNames = [ + [\T_STRING, '__construct'], + [\T_STRING, '__destruct'], + [\T_STRING, '__clone'], + ]; + + /** + * @var array + */ + private array $skippedTypes = [ + 'resource' => true, + 'null' => true, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Takes `@return` annotation of non-mixed types and adjusts accordingly the function signature.', + [ + new CodeSample( + <<<'PHP' + false], + ), + new CodeSample( + <<<'PHP' + false], + ), + new VersionSpecificCodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + /** + * {@inheritdoc} + * + * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, ReturnToYieldFromFixer, ReturnTypeDeclarationFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 13; + } + + protected function isSkippedType(string $type): bool + { + return isset($this->skippedTypes[$type]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensToInsert = []; + $typesToExclude = []; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); + + continue; + } + + if (!$tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { + continue; + } + + $funcName = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, false)) { + continue; + } + + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + if (null === $docCommentIndex) { + continue; + } + + $returnTypeAnnotations = $this->getAnnotationsFromDocComment('return', $tokens, $docCommentIndex); + if (1 !== \count($returnTypeAnnotations)) { + continue; + } + + $returnTypeAnnotation = $returnTypeAnnotations[0]; + + $typesExpression = $returnTypeAnnotation->getTypeExpression(); + + if (null === $typesExpression) { + continue; + } + + $typeInfo = $this->getCommonTypeInfo($typesExpression, true); + $unionTypes = null; + + if (null === $typeInfo) { + $unionTypes = $this->getUnionTypes($typesExpression, true); + } + + if (null === $typeInfo && null === $unionTypes) { + continue; + } + + if (null !== $typeInfo) { + $returnType = $typeInfo['commonType']; + $isNullable = $typeInfo['isNullable']; + } else { // null !== $unionTypes, because of previous 2 ifs + $returnType = $unionTypes; + $isNullable = false; + } + + if (\in_array($returnType, $typesToExclude, true)) { + continue; + } + + $paramsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); + $paramsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $paramsStartIndex); + + $bodyStartIndex = $tokens->getNextTokenOfKind($paramsEndIndex, ['{', ';', [\T_DOUBLE_ARROW]]); + + if ($this->hasReturnTypeHint($tokens, $bodyStartIndex)) { + continue; + } + + if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $returnType))) { + continue; + } + + $tokensToInsert[$paramsEndIndex + 1] = array_merge( + [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([\T_WHITESPACE, ' ']), + ], + $this->createTypeDeclarationTokens($returnType, $isNullable), + ); + } + + $tokens->insertSlices($tokensToInsert); + } + + protected function createTokensFromRawType(string $type): Tokens + { + $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); + $typeTokens->clearRange(0, 7); + $typeTokens->clearRange(\count($typeTokens) - 3, \count($typeTokens) - 1); + $typeTokens->clearEmptyTokens(); + + return $typeTokens; + } + + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index): bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php new file mode 100644 index 0000000..a930be5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php @@ -0,0 +1,260 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RegularCallableCallFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Callables must be called without using `call_user_func*` when possible.', + [ + new CodeSample( + <<<'PHP' + \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NativeFunctionInvocationFixer. + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equalsAny([[\T_STRING, 'call_user_func'], [\T_STRING, 'call_user_func_array']], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; // redeclare/override + } + + $openParenthesis = $tokens->getNextMeaningfulToken($index); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis); + + if (1 > \count($arguments)) { + return; // no arguments! + } + + $this->processCall($tokens, $index, $arguments); + } + } + + /** + * @param non-empty-array $arguments + */ + private function processCall(Tokens $tokens, int $index, array $arguments): void + { + $firstArgIndex = $tokens->getNextMeaningfulToken( + $tokens->getNextMeaningfulToken($index), + ); + + $firstArgToken = $tokens[$firstArgIndex]; + + if ($firstArgToken->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex); + + if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) { + return; // first argument is an expression like `call_user_func("foo"."bar", ...)`, not supported! + } + + $firstArgTokenContent = $firstArgToken->getContent(); + + if (!$this->isValidFunctionInvoke($firstArgTokenContent)) { + return; + } + + $newCallTokens = Tokens::fromCode('getContent()), 1, -1).'();'); + $newCallTokensSize = $newCallTokens->count(); + $newCallTokens->clearAt(0); + $newCallTokens->clearRange($newCallTokensSize - 3, $newCallTokensSize - 1); + $newCallTokens->clearEmptyTokens(); + + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgIndex); + } elseif ( + $firstArgToken->isGivenKind(\T_FUNCTION) + || ( + $firstArgToken->isGivenKind(\T_STATIC) + && $tokens[$tokens->getNextMeaningfulToken($firstArgIndex)]->isGivenKind(\T_FUNCTION) + ) + ) { + $firstArgEndIndex = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_BRACE, + $tokens->getNextTokenOfKind($firstArgIndex, ['{']), + ); + + $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); + $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); + $newCallTokens->insertAt(0, new Token('(')); + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); + } elseif ($firstArgToken->isGivenKind(\T_VARIABLE)) { + $firstArgEndIndex = reset($arguments); + + // check if the same variable is used multiple times and if so do not fix + + foreach ($arguments as $argumentStart => $argumentEnd) { + if ($firstArgEndIndex === $argumentEnd) { + continue; + } + + for ($i = $argumentStart; $i <= $argumentEnd; ++$i) { + if ($tokens[$i]->equals($firstArgToken)) { + return; + } + } + } + + // check if complex statement and if so wrap the call in () if on PHP 7 or up, else do not fix + + $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); + $complex = false; + + for ($newCallIndex = \count($newCallTokens) - 1; $newCallIndex >= 0; --$newCallIndex) { + if ($newCallTokens[$newCallIndex]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_VARIABLE])) { + continue; + } + + $blockType = Tokens::detectBlockType($newCallTokens[$newCallIndex]); + + if (null !== $blockType && (Tokens::BLOCK_TYPE_INDEX_BRACE === $blockType['type'] || Tokens::BLOCK_TYPE_INDEX_BRACKET === $blockType['type'])) { + $newCallIndex = $newCallTokens->findBlockStart($blockType['type'], $newCallIndex); + + continue; + } + + $complex = true; + + break; + } + + if ($complex) { + $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); + $newCallTokens->insertAt(0, new Token('(')); + } + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); + } + } + + private function replaceCallUserFuncWithCallback(Tokens $tokens, int $callIndex, Tokens $newCallTokens, int $firstArgStartIndex, int $firstArgEndIndex): void + { + $tokens->clearRange($firstArgStartIndex, $firstArgEndIndex); + + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex); + $afterFirstArgToken = $tokens[$afterFirstArgIndex]; + + if ($afterFirstArgToken->equals(',')) { + $useEllipsis = $tokens[$callIndex]->equals([\T_STRING, 'call_user_func_array'], false); + + if ($useEllipsis) { + $secondArgIndex = $tokens->getNextMeaningfulToken($afterFirstArgIndex); + $tokens->insertAt($secondArgIndex, new Token([\T_ELLIPSIS, '...'])); + } + + $tokens->clearAt($afterFirstArgIndex); + $tokens->removeTrailingWhitespace($afterFirstArgIndex); + } + + $tokens->overrideRange($callIndex, $callIndex, $newCallTokens); + $prevIndex = $tokens->getPrevMeaningfulToken($callIndex); + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + } + + private function getTokensSubcollection(Tokens $tokens, int $indexStart, int $indexEnd): Tokens + { + $size = $indexEnd - $indexStart + 1; + $subCollection = new Tokens($size); + + for ($i = 0; $i < $size; ++$i) { + $toClone = $tokens[$i + $indexStart]; + $subCollection[$i] = clone $toClone; + } + + return $subCollection; + } + + private function isValidFunctionInvoke(string $name): bool + { + if (\strlen($name) < 3 || 'b' === $name[0] || 'B' === $name[0]) { + return false; + } + + $name = substr($name, 1, -1); + + if ($name !== trim($name)) { + return false; + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php new file mode 100644 index 0000000..8d02fd6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * space_before?: 'none'|'one', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * space_before: 'none'|'one', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReturnTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adjust spacing around colon in return type declarations and backed enum types.', + [ + new CodeSample( + " 'none'], + ), + new CodeSample( + " 'one'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer, VoidReturnFixer. + */ + public function getPriority(): int + { + return -17; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(CT::T_TYPE_COLON); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $oneSpaceBefore = 'one' === $this->configuration['space_before']; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + if (!$tokens[$index]->isGivenKind(CT::T_TYPE_COLON)) { + continue; + } + + $previousIndex = $index - 1; + $previousToken = $tokens[$previousIndex]; + + if ($previousToken->isWhitespace()) { + if (!$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + if ($oneSpaceBefore) { + $tokens[$previousIndex] = new Token([\T_WHITESPACE, ' ']); + } else { + $tokens->clearAt($previousIndex); + } + } + } elseif ($oneSpaceBefore) { + $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); + + if ($tokenWasAdded) { + ++$limit; + } + + ++$index; + } + + ++$index; + + $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); + + if ($tokenWasAdded) { + ++$limit; + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space_before', 'Spacing to apply before colon.')) + ->setAllowedValues(['one', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php new file mode 100644 index 0000000..7d9eeb8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php @@ -0,0 +1,149 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleLineThrowFixer extends AbstractFixer +{ + private const REMOVE_WHITESPACE_AFTER_TOKENS = ['[']; + private const REMOVE_WHITESPACE_AROUND_TOKENS = ['(', [\T_DOUBLE_COLON]]; + private const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Throwing exception must be done in single line.', + [ + new CodeSample("isTokenKindFound(\T_THROW); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ConcatSpaceFixer. + */ + public function getPriority(): int + { + return 36; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_THROW)) { + continue; + } + + $endCandidateIndex = $tokens->getNextMeaningfulToken($index); + + while (!$tokens[$endCandidateIndex]->equalsAny([')', ']', ',', ';', [\T_CLOSE_TAG]])) { + $blockType = Tokens::detectBlockType($tokens[$endCandidateIndex]); + + if (null !== $blockType) { + if (Tokens::BLOCK_TYPE_BRACE === $blockType['type'] || !$blockType['isStart']) { + break; + } + + $endCandidateIndex = $tokens->findBlockEnd($blockType['type'], $endCandidateIndex); + } + + $endCandidateIndex = $tokens->getNextMeaningfulToken($endCandidateIndex); + } + + $this->trimNewLines($tokens, $index, $tokens->getPrevMeaningfulToken($endCandidateIndex)); + } + } + + private function trimNewLines(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + $content = $tokens[$index]->getContent(); + + if ($tokens[$index]->isGivenKind(\T_COMMENT)) { + if (str_starts_with($content, '//')) { + $content = '/*'.substr($content, 2).' */'; + $tokens->clearAt($index + 1); + } elseif (str_starts_with($content, '#')) { + $content = '/*'.substr($content, 1).' */'; + $tokens->clearAt($index + 1); + } elseif (Preg::match('/\R/', $content)) { + $content = Preg::replace('/\R/', ' ', $content); + } + + $tokens[$index] = new Token([\T_COMMENT, $content]); + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_WHITESPACE)) { + continue; + } + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $prevIndex = $tokens->getNonEmptySibling($index, -1); + + if ($this->isPreviousTokenToClear($tokens[$prevIndex])) { + $tokens->clearAt($index); + + continue; + } + + $nextIndex = $tokens->getNonEmptySibling($index, 1); + + if ( + $this->isNextTokenToClear($tokens[$nextIndex]) + && !$tokens[$prevIndex]->isGivenKind(\T_FUNCTION) + ) { + $tokens->clearAt($index); + + continue; + } + + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + } + + private function isPreviousTokenToClear(Token $token): bool + { + return $token->equalsAny([...self::REMOVE_WHITESPACE_AFTER_TOKENS, ...self::REMOVE_WHITESPACE_AROUND_TOKENS]) || $token->isObjectOperator(); + } + + private function isNextTokenToClear(Token $token): bool + { + return $token->equalsAny([...self::REMOVE_WHITESPACE_AROUND_TOKENS, ...self::REMOVE_WHITESPACE_BEFORE_TOKENS]) || $token->isObjectOperator(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php new file mode 100644 index 0000000..ef422a1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php @@ -0,0 +1,172 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StaticLambdaFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Lambdas not (indirectly) referencing `$this` must be declared `static`.', + [ + new CodeSample( + <<<'PHP' + bindTo(new stdClass()); + + PHP, + ), + ], + null, + 'Risky when using `->bindTo` on lambdas without referencing to `$this`.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run after StaticPrivateMethodFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + $expectedFunctionKinds = [\T_FUNCTION, \T_FN]; + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind($expectedFunctionKinds) || !$analyzer->isLambda($index)) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prev]->isGivenKind(\T_STATIC)) { + continue; // lambda is already 'static' + } + + $argumentsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); + $argumentsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $argumentsStartIndex); + + // figure out where the lambda starts and ends + + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, ['{']); + $lambdaEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $lambdaOpenIndex); + } else { // T_FN + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, [[\T_DOUBLE_ARROW]]); + $lambdaEndIndex = $analyzer->getLastTokenIndexOfArrowFunction($index); + } + + if ($this->hasPossibleReferenceToThis($tokens, $lambdaOpenIndex, $lambdaEndIndex)) { + continue; + } + + // make the lambda static + $tokens->insertAt( + $index, + [ + new Token([\T_STATIC, 'static']), + new Token([\T_WHITESPACE, ' ']), + ], + ); + + $index -= 4; // fixed after a lambda, closes candidate is at least 4 tokens before that + } + } + + /** + * Returns 'true' if there is a possible reference to '$this' within the given tokens index range. + */ + private function hasPossibleReferenceToThis(Tokens $tokens, int $startIndex, int $endIndex): bool + { + for ($i = $startIndex; $i <= $endIndex; ++$i) { + if ($tokens[$i]->isGivenKind(\T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { + return true; // directly accessing '$this' + } + + if ($tokens[$i]->isGivenKind([ + \T_INCLUDE, // loading additional symbols we cannot analyse here + \T_INCLUDE_ONCE, // " + \T_REQUIRE, // " + \T_REQUIRE_ONCE, // " + CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case + \T_EVAL, // "$c = eval('return $this;');" case + ])) { + return true; + } + + if ($tokens[$i]->isClassy()) { + $openBraceIndex = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->getNextMeaningfulToken($i); + if ($i <= $openBraceIndex && $this->hasPossibleReferenceToThis( + $tokens, + $i, + $openBraceIndex, + )) { + return true; + } + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $openBraceIndex); + + continue; + } + + if ($tokens[$i]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + return true; // "$$a" case + } + } + + if ($tokens[$i]->equals([\T_STRING, 'parent'], false)) { + return true; // parent:: case + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php new file mode 100644 index 0000000..72f2d98 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php @@ -0,0 +1,210 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class UseArrowFunctionsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Anonymous functions with return as the only statement must use arrow functions.', + [ + new CodeSample( + <<<'SAMPLE' + isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before FunctionDeclarationFixer. + */ + public function getPriority(): int + { + return 32; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$analyzer->isLambda($index)) { + continue; + } + + // Find parameters + + $parametersStart = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$parametersStart]->isGivenKind(CT::T_RETURN_REF)) { + $parametersStart = $tokens->getNextMeaningfulToken($parametersStart); + } + + $parametersEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $parametersStart); + + // Find `use ()` start and end + // Abort if it contains reference variables + + $next = $tokens->getNextMeaningfulToken($parametersEnd); + + $useStart = null; + $useEnd = null; + + if ($tokens[$next]->isGivenKind(CT::T_USE_LAMBDA)) { + $useStart = $next; + + if ($tokens[$useStart - 1]->isGivenKind(\T_WHITESPACE)) { + --$useStart; + } + + $next = $tokens->getNextMeaningfulToken($next); + + while (!$tokens[$next]->equals(')')) { + if ($tokens[$next]->equals('&')) { + // variables used by reference are not supported by arrow functions + continue 2; + } + + $next = $tokens->getNextMeaningfulToken($next); + } + + $useEnd = $next; + $next = $tokens->getNextMeaningfulToken($next); + } + + // Find opening brace and following `return` + // Abort if there is more than whitespace between them (like comments) + + $braceOpen = $tokens[$next]->equals('{') ? $next : $tokens->getNextTokenOfKind($next, ['{']); + $return = $braceOpen + 1; + + if ($tokens[$return]->isGivenKind(\T_WHITESPACE)) { + ++$return; + } + + if (!$tokens[$return]->isGivenKind(\T_RETURN)) { + continue; + } + + // Find semicolon of `return` statement + + $semicolon = $tokens->getNextTokenOfKind($return, ['{', ';']); + + if (!$tokens[$semicolon]->equals(';')) { + continue; + } + + // Find closing brace + // Abort if there is more than whitespace between semicolon and closing brace + + $braceClose = $semicolon + 1; + + if ($tokens[$braceClose]->isGivenKind(\T_WHITESPACE)) { + ++$braceClose; + } + + if (!$tokens[$braceClose]->equals('}')) { + continue; + } + + // Abort if closure has `use()` clause and return statement includes external files. + // Converting such closures to arrow functions changes behaviour as the used variables + // are no longer exposed to the included file. + if (null !== $useStart && $this->containsIncludeOrRequire($tokens, $return, $semicolon)) { + continue; + } + + // Transform the function to an arrow function + $this->transform($tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose); + } + } + + private function transform(Tokens $tokens, int $index, ?int $useStart, ?int $useEnd, int $braceOpen, int $return, int $semicolon, int $braceClose): void + { + $tokensToInsert = [new Token([\T_DOUBLE_ARROW, '=>'])]; + + if ($tokens->getNextMeaningfulToken($return) === $semicolon) { + $tokensToInsert[] = new Token([\T_WHITESPACE, ' ']); + $tokensToInsert[] = new Token([\T_STRING, 'null']); + } + + $tokens->clearRange($semicolon, $braceClose - 1); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceClose); + + $tokens->clearRange($braceOpen + 1, $return); + $tokens->overrideRange($braceOpen, $braceOpen, $tokensToInsert); + + if (null !== $useStart) { + $tokens->clearRange($useStart, $useEnd); + } + + $tokens[$index] = new Token([\T_FN, 'fn']); + } + + /** + * Check if the return statement contains include/include_once/require/require_once. + */ + private function containsIncludeOrRequire(Tokens $tokens, int $start, int $end): bool + { + for ($i = $start; $i < $end; ++$i) { + if ($tokens[$i]->isGivenKind([\T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE])) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php new file mode 100644 index 0000000..4ef3cc2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php @@ -0,0 +1,308 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * fix_lambda?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * fix_lambda: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Mark Nielsen + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class VoidReturnFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const PREVIOUS_TOKENS = [ + \T_ABSTRACT, + \T_FINAL, + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_STATIC, + FCT::T_ATTRIBUTE, + ]; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + $sharedSnipped = <<<'PHP' + false], + ), + ], + null, + 'Modifies the signature of functions.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocNoEmptyReturnFixer, ReturnTypeDeclarationFixer. + * Must run after NoSuperfluousPhpdocTagsFixer, SimplifiedNullReturnFixer. + */ + public function getPriority(): int + { + return 5; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_FUNCTION); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_lambda', 'Whether to fix lambda functions as well.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + if ( + false === $this->configuration['fix_lambda'] + && $this->tokensAnalyzer->isLambda($index) + ) { + continue; + } + + $functionName = $tokens->getNextMeaningfulToken($index); + // These cause syntax errors. + if ($tokens[$functionName]->equalsAny([ + [\T_STRING, '__clone'], + [\T_STRING, '__construct'], + [\T_STRING, '__debugInfo'], + [\T_STRING, '__destruct'], + [\T_STRING, '__isset'], + [\T_STRING, '__serialize'], + [\T_STRING, '__set_state'], + [\T_STRING, '__sleep'], + [\T_STRING, '__toString'], + ], false)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($this->hasReturnTypeHint($tokens, $startIndex)) { + continue; + } + + if ($tokens[$startIndex]->equals(';')) { + // No function body defined, fallback to PHPDoc. + if ($this->hasVoidReturnAnnotation($tokens, $index)) { + $this->fixFunctionDefinition($tokens, $startIndex); + } + + continue; + } + + if ($this->hasReturnAnnotation($tokens, $index)) { + continue; + } + + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $startIndex); + + if ($this->hasVoidReturn($tokens, $startIndex, $endIndex)) { + $this->fixFunctionDefinition($tokens, $startIndex); + } + } + } + + /** + * Determine whether there is a non-void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasReturnAnnotation(Tokens $tokens, int $index): bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] !== $return->getTypes()) { + return true; + } + } + + return false; + } + + /** + * Determine whether there is a void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasVoidReturnAnnotation(Tokens $tokens, int $index): bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] === $return->getTypes()) { + return true; + } + } + + return false; + } + + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index): bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } + + /** + * Determine whether the function has a void return. + * + * @param int $startIndex Start of function body + * @param int $endIndex End of function body + */ + private function hasVoidReturn(Tokens $tokens, int $startIndex, int $endIndex): bool + { + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ( + // skip anonymous classes + ($tokens[$i]->isGivenKind(\T_CLASS) && $this->tokensAnalyzer->isAnonymousClass($i)) + // skip lambda functions + || ($tokens[$i]->isGivenKind(\T_FUNCTION) && $this->tokensAnalyzer->isLambda($i)) + ) { + $i = $tokens->getNextTokenOfKind($i, ['{']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $i); + + continue; + } + + if ($tokens[$i]->isGivenKind([\T_YIELD, \T_YIELD_FROM])) { + return false; // Generators cannot return void. + } + + if (!$tokens[$i]->isGivenKind(\T_RETURN)) { + continue; + } + + $i = $tokens->getNextMeaningfulToken($i); + if (!$tokens[$i]->equals(';')) { + return false; + } + } + + return true; + } + + /** + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function fixFunctionDefinition(Tokens $tokens, int $index): void + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $tokens->insertAt($endFuncIndex + 1, [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_STRING, 'void']), + ]); + } + + /** + * Find all the return annotations in the function's PHPDoc comment. + * + * @param int $index The index of the function token + * + * @return list + */ + private function findReturnAnnotations(Tokens $tokens, int $index): array + { + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind(self::PREVIOUS_TOKENS)); + + if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + return []; + } + + $doc = new DocBlock($tokens[$index]->getContent()); + + return $doc->getAnnotationsOfType('return'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php new file mode 100644 index 0000000..2748e54 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php @@ -0,0 +1,1029 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Processor\ImportProcessor; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * import_symbols?: bool, + * leading_backslash_in_global_namespace?: bool, + * phpdoc_tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * import_symbols: bool, + * leading_backslash_in_global_namespace: bool, + * phpdoc_tags: list, + * } + * @phpstan-type _Uses array{ + * constant?: array, + * class?: array, + * function?: array + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author VeeWee + * @author Tomas Jadrny + * @author Greg Korba + * @author SpacePossum + * @author Michael Vorisek + * + * @phpstan-import-type _ImportType from \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FullyQualifiedStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER + .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; + private const CLASSY_KINDS = [\T_CLASS, \T_INTERFACE, \T_TRAIT, FCT::T_ENUM]; + + /** + * @var null|array{ + * constant?: list, + * class?: list, + * function?: list + * } + */ + private ?array $discoveredSymbols; + + /** + * @var array{ + * constant?: array, + * class?: array, + * function?: array + * } + */ + private array $symbolsForImport = []; + + /** + * @var array, array> + */ + private array $reservedIdentifiersByLevel; + + /** + * @var array{ + * constant?: array, + * class?: array, + * function?: array + * } + */ + private array $cacheUsesLast = []; + + /** + * @var array{ + * constant?: array, + * class?: array, + * function?: array + * } + */ + private array $cacheUseNameByShortNameLower; + + /** @var _Uses */ + private array $cacheUseShortNameByName; + + /** @var _Uses */ + private array $cacheUseShortNameByNormalizedName; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes the leading part of fully qualified symbol references if a given symbol is imported or belongs to the current namespace.', + [ + new CodeSample( + <<<'PHP' + baz = $baz; + } + + /** + * @return \Foo\Bar\Baz + */ + public function getBaz() { + return $this->baz; + } + + public function doX(\Foo\Bar $foo, \Exception $e): \Foo\Bar\Baz + { + try {} + catch (\Foo\SomeException $e) {} + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, OrderedAttributesFixer, OrderedImportsFixer, OrderedInterfacesFixer, StatementIndentationFixer. + * Must run after ClassKeywordFixer, PhpUnitAttributesFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer. + */ + public function getPriority(): int + { + return 7; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([ + CT::T_USE_TRAIT, + FCT::T_ATTRIBUTE, + \T_CATCH, + \T_DOUBLE_COLON, + \T_DOC_COMMENT, + \T_EXTENDS, + \T_FUNCTION, + \T_IMPLEMENTS, + \T_INSTANCEOF, + \T_NEW, + \T_VARIABLE, + ]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'leading_backslash_in_global_namespace', + 'Whether FQCN is prefixed with backslash when that FQCN is used in global namespace context.', + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'import_symbols', + 'Whether FQCNs should be automatically imported.', + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder( + 'phpdoc_tags', + 'Collection of PHPDoc annotation tags where FQCNs should be processed. As of now only simple tags with `@tag \F\Q\C\N` format are supported (no complex types).', + )) + ->setAllowedTypes(['string[]']) + ->setDefault([ + 'param', + 'phpstan-param', + 'phpstan-property', + 'phpstan-property-read', + 'phpstan-property-write', + 'phpstan-return', + 'phpstan-var', + 'property', + 'property-read', + 'property-write', + 'psalm-param', + 'psalm-property', + 'psalm-property-read', + 'psalm-property-write', + 'psalm-return', + 'psalm-var', + 'return', + 'see', + 'throws', + 'var', + ]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $functionsAnalyzer = new FunctionsAnalyzer(); + + $this->symbolsForImport = []; + + foreach ($tokens->getNamespaceDeclarations() as $namespaceIndex => $namespace) { + $namespace = $tokens->getNamespaceDeclarations()[$namespaceIndex]; + + $namespaceName = $namespace->getFullName(); + + $uses = []; + $lastUse = null; + + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace, true) as $use) { + if (!$use->isClass()) { + continue; + } + + $fullName = ltrim($use->getFullName(), '\\'); + \assert('' !== $fullName); + $uses[$use->getHumanFriendlyType()][$fullName] = $use->getShortName(); + $lastUse = $use; + } + + $indexDiff = 0; + foreach (true === $this->configuration['import_symbols'] ? [true, false] : [false] as $discoverSymbolsPhase) { + $this->discoveredSymbols = $discoverSymbolsPhase ? [] : null; + + $openedCurlyBrackets = 0; + $this->reservedIdentifiersByLevel = []; + + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex() + $indexDiff; ++$index) { + $origSize = \count($tokens); + $token = $tokens[$index]; + + if ($token->equals('{')) { + ++$openedCurlyBrackets; + } elseif ($token->equals('}')) { + unset($this->reservedIdentifiersByLevel[$openedCurlyBrackets]); + --$openedCurlyBrackets; + \assert($openedCurlyBrackets >= 0); + } elseif ($token->isGivenKind(\T_VARIABLE)) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_STRING)) { + $this->fixPrevName($tokens, $index, $uses, $namespaceName); + } + } elseif ($token->isGivenKind(\T_DOUBLE_COLON)) { + $this->fixPrevName($tokens, $index, $uses, $namespaceName); + } elseif ($token->isGivenKind(\T_FUNCTION)) { + $this->fixFunction($functionsAnalyzer, $tokens, $index, $uses, $namespaceName); + } elseif ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $this->fixAttribute($tokens, $index, $uses, $namespaceName); + } elseif ($token->isGivenKind(\T_CATCH)) { + $this->fixCatch($tokens, $index, $uses, $namespaceName); + } elseif ($discoverSymbolsPhase && $token->isGivenKind(self::CLASSY_KINDS)) { + $this->fixNextName($tokens, $index, $uses, $namespaceName); + } elseif ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { + $this->fixExtendsImplements($tokens, $index, $uses, $namespaceName); + } elseif ($token->isGivenKind([\T_INSTANCEOF, \T_NEW, CT::T_USE_TRAIT, CT::T_TYPE_COLON])) { + $this->fixNextName($tokens, $index, $uses, $namespaceName); + } elseif ($discoverSymbolsPhase && $token->isGivenKind(\T_COMMENT) && Preg::match('/#\[\s*('.self::REGEX_CLASS.')/', $token->getContent(), $matches)) { // @TODO: drop when PHP 8.0+ is required + $attributeClass = $matches[1]; + $this->determineShortType($attributeClass, 'class', $uses, $namespaceName); + } elseif ($token->isGivenKind(\T_DOC_COMMENT)) { + Preg::matchAll('/\*\h*@(?:psalm-|phpstan-)?(?:template(?:-covariant|-contravariant)?|(?:import-)?type)\h+('.TypeExpression::REGEX_IDENTIFIER.')(?!\S)/i', $token->getContent(), $matches); + foreach ($matches[1] as $reservedIdentifier) { + $this->reservedIdentifiersByLevel[$openedCurlyBrackets + 1][$reservedIdentifier] = true; + } + + $this->fixPhpDoc($tokens, $index, $uses, $namespaceName); + } + + $indexDiff += \count($tokens) - $origSize; + } + + $this->reservedIdentifiersByLevel = []; + + if ($discoverSymbolsPhase) { + $this->setupUsesFromDiscoveredSymbols($uses, $namespaceName); + } + } + + if ([] !== $this->symbolsForImport) { // @phpstan-ignore-line notIdentical.alwaysFalse PHP started to complain, please fix me + if (null !== $lastUse) { + $atIndex = $lastUse->getEndIndex() + 1; + } elseif (0 !== $namespace->getEndIndex()) { + $atIndex = $namespace->getEndIndex() + 1; + } else { + $firstTokenIndex = $tokens->getNextMeaningfulToken($namespace->getScopeStartIndex()); + if (null !== $firstTokenIndex && $tokens[$firstTokenIndex]->isGivenKind(\T_DECLARE)) { + $atIndex = $tokens->getNextTokenOfKind($firstTokenIndex, [';']) + 1; + } else { + $atIndex = $namespace->getScopeStartIndex() + 1; + } + } + + // Insert all registered FQCNs + $this->createImportProcessor()->insertImports($tokens, $this->symbolsForImport, $atIndex); + + $this->symbolsForImport = []; + } + } + } + + /** + * @param _Uses $uses + */ + private function refreshUsesCache(array $uses): void + { + if ($this->cacheUsesLast === $uses) { + return; + } + + $this->cacheUsesLast = $uses; + + $this->cacheUseNameByShortNameLower = []; + $this->cacheUseShortNameByName = []; + $this->cacheUseShortNameByNormalizedName = []; + + foreach ($uses as $kind => $kindUses) { + foreach ($kindUses as $useLongName => $useShortName) { + $this->cacheUseNameByShortNameLower[$kind][strtolower($useShortName)] = $useLongName; + $this->cacheUseShortNameByName[$kind][$useLongName] = $useShortName; + + /** @var non-empty-string */ + $normalizedUseLongName = $this->normalizeFqcn($useLongName); + $this->cacheUseShortNameByNormalizedName[$kind][$normalizedUseLongName] = $useShortName; + } + } + } + + private function isReservedIdentifier(string $symbol): bool + { + if (str_contains($symbol, '\\')) { // optimization only + return false; + } + + if ((new TypeAnalysis($symbol))->isReservedType()) { + return true; + } + + foreach ($this->reservedIdentifiersByLevel as $reservedIdentifiers) { + if (isset($reservedIdentifiers[$symbol])) { + return true; + } + } + + return false; + } + + /** + * Resolve absolute or relative symbol to normalized FQCN. + * + * @param _ImportType $importKind + * @param _Uses $uses + * + * @return non-empty-string + */ + private function resolveSymbol(string $symbol, string $importKind, array $uses, string $namespaceName): string + { + if (str_starts_with($symbol, '\\')) { + return substr($symbol, 1); // @phpstan-ignore return.type + } + + if ($this->isReservedIdentifier($symbol)) { + return $symbol; // @phpstan-ignore return.type + } + + $this->refreshUsesCache($uses); + + $symbolArr = explode('\\', $symbol, 2); + $shortStartNameLower = strtolower($symbolArr[0]); + if (isset($this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower])) { + return $this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower].(isset($symbolArr[1]) ? '\\'.$symbolArr[1] : ''); + } + + return ('' !== $namespaceName ? $namespaceName.'\\' : '').$symbol; // @phpstan-ignore return.type + } + + /** + * Shorten normalized FQCN as much as possible. + * + * @param _ImportType $importKind + * @param _Uses $uses + */ + private function shortenSymbol(string $fqcn, string $importKind, array $uses, string $namespaceName): string + { + if ($this->isReservedIdentifier($fqcn)) { + return $fqcn; + } + + $this->refreshUsesCache($uses); + + $res = null; + + // try to shorten the name using namespace + $iMin = 0; + if (str_starts_with($fqcn, $namespaceName.'\\')) { + $tmpRes = substr($fqcn, \strlen($namespaceName) + 1); + if (!isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $tmpRes, 2)[0])]) && !$this->isReservedIdentifier($tmpRes)) { + $res = $tmpRes; + $iMin = substr_count($namespaceName, '\\') + 1; + } + } + + // try to shorten the name using uses + $tmp = $fqcn; + for ($i = substr_count($fqcn, '\\'); $i >= $iMin; --$i) { + if (isset($this->cacheUseShortNameByName[$importKind][$tmp])) { + $tmpRes = $this->cacheUseShortNameByName[$importKind][$tmp].substr($fqcn, \strlen($tmp)); + if (!$this->isReservedIdentifier($tmpRes)) { + $res = $tmpRes; + + break; + } + } + + if ($i > 0) { + \assert(false !== strrpos($tmp, '\\')); + $tmp = substr($tmp, 0, strrpos($tmp, '\\')); + } + } + + if (null === $res) { + $normalizedFqcn = $this->normalizeFqcn($fqcn); + $tmpRes = $this->cacheUseShortNameByNormalizedName[$importKind][$normalizedFqcn] ?? null; + if (null !== $tmpRes && !$this->isReservedIdentifier($tmpRes)) { + $res = $tmpRes; + } + } + + // shortening is not possible, add leading backslash if needed + if (null === $res) { + $res = $fqcn; + if ('' !== $namespaceName + || true === $this->configuration['leading_backslash_in_global_namespace'] + || isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $res, 2)[0])]) + ) { + $res = '\\'.$res; + } + } + + return $res; + } + + /** + * @param _Uses $uses + */ + private function setupUsesFromDiscoveredSymbols(array &$uses, string $namespaceName): void + { + foreach ($this->discoveredSymbols as $kind => $discoveredSymbols) { + $discoveredFqcnByShortNameLower = []; + + if ('' === $namespaceName) { + foreach ($discoveredSymbols as $symbol) { + if (!str_starts_with($symbol, '\\')) { + $shortStartName = explode('\\', ltrim($symbol, '\\'), 2)[0]; + \assert('' !== $shortStartName); + $shortStartNameLower = strtolower($shortStartName); + $discoveredFqcnByShortNameLower[$kind][$shortStartNameLower] = $this->resolveSymbol($shortStartName, $kind, $uses, $namespaceName); + } + } + } + + foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) { + $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] = $useLongName; + } + + $useByShortNameLower = []; + foreach ($uses[$kind] ?? [] as $useShortName) { + $useByShortNameLower[strtolower($useShortName)] = true; + } + + uasort($discoveredSymbols, static function ($a, $b) { + $res = str_starts_with($a, '\\') <=> str_starts_with($b, '\\'); + if (0 !== $res) { + return $res; + } + + return substr_count($a, '\\') <=> substr_count($b, '\\'); + }); + foreach ($discoveredSymbols as $symbol) { + while (true) { + $shortEndNameLower = strtolower(str_contains($symbol, '\\') ? substr($symbol, (int) strrpos($symbol, '\\') + 1) : $symbol); + if (!isset($discoveredFqcnByShortNameLower[$kind][$shortEndNameLower])) { + $shortStartNameLower = strtolower(explode('\\', ltrim($symbol, '\\'), 2)[0]); + if (str_starts_with($symbol, '\\') || ('' === $namespaceName && !isset($useByShortNameLower[$shortStartNameLower])) + || !str_contains($symbol, '\\') + ) { + $discoveredFqcnByShortNameLower[$kind][$shortEndNameLower] = $this->resolveSymbol($symbol, $kind, $uses, $namespaceName); + + break; + } + } + // else short name collision - keep unimported + + if (str_starts_with($symbol, '\\') || '' === $namespaceName || !str_contains($symbol, '\\')) { + break; + } + + \assert(false !== strrpos($symbol, '\\')); + $symbol = substr($symbol, 0, strrpos($symbol, '\\')); + } + } + + foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) { + $discoveredLongName = $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] ?? null; + if (strtolower($discoveredLongName) === strtolower($useLongName)) { + unset($discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)]); + } + } + + foreach ($discoveredFqcnByShortNameLower[$kind] ?? [] as $fqcn) { + $shortenedName = ltrim($this->shortenSymbol($fqcn, $kind, [], $namespaceName), '\\'); + if (str_contains($shortenedName, '\\')) { // prevent importing non-namespaced names in global namespace + $shortEndName = str_contains($fqcn, '\\') ? substr($fqcn, (int) strrpos($fqcn, '\\') + 1) : $fqcn; + \assert('' !== $shortEndName); + $uses[$kind][$fqcn] = $shortEndName; + $this->symbolsForImport[$kind][$shortEndName] = $fqcn; + } + } + + if (isset($this->symbolsForImport[$kind])) { + ksort($this->symbolsForImport[$kind], \SORT_NATURAL); + } + } + } + + /** + * @param _Uses $uses + */ + private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); + + foreach ($arguments as $i => $argument) { + $argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i]; + + if ($argument->hasTypeAnalysis()) { + $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName); + } + } + + $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null !== $returnTypeAnalysis) { + $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName); + } + } + + /** + * @param _Uses $uses + */ + private function fixPhpDoc(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $allowedTags = $this->configuration['phpdoc_tags']; + + if ([] === $allowedTags) { + return; + } + + $phpDoc = $tokens[$index]; + $phpDocContent = $phpDoc->getContent(); + $phpDocContentNew = Preg::replaceCallback('/([*{]\h*@)(\S+)(\h+)('.TypeExpression::REGEX_TYPES.')(?!(?!\})\S)/', function ($matches) use ($allowedTags, $uses, $namespaceName) { + if (!\in_array($matches[2], $allowedTags, true)) { + return $matches[0]; + } + + return $matches[1].$matches[2].$matches[3].$this->fixPhpDocType($matches[4], $uses, $namespaceName); + }, $phpDocContent); + + if (\in_array('see', $allowedTags, true)) { + $phpDocContentNew = Preg::replaceCallback( + '/([*{]\h*)@see(\h+)('.self::REGEX_CLASS.')(::(?:\$\w+|\w+\(\)))(?!(?!\})\S)/', + fn ($matches) => $matches[1].'@see'.$matches[2].$this->fixPhpDocType($matches[3], $uses, $namespaceName).$matches[5], + $phpDocContentNew, + ); + } + + if ($phpDocContentNew !== $phpDocContent) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $phpDocContentNew]); + } + } + + /** + * @param _Uses $uses + */ + private function fixPhpDocType(string $type, array $uses, string $namespaceName): string + { + $typeExpression = new TypeExpression($type, null, []); + + $typeExpression = $typeExpression->mapTypes(function (TypeExpression $type) use ($uses, $namespaceName) { + $currentTypeValue = $type->toString(); + + if ($type->isCompositeType() || !Preg::match('/^'.self::REGEX_CLASS.'$/', $currentTypeValue) || \in_array($currentTypeValue, ['min', 'max'], true)) { + return $type; + } + + $shortTokens = $this->determineShortType($currentTypeValue, 'class', $uses, $namespaceName); + + if (null === $shortTokens) { + return $type; + } + + $newTypeValue = implode('', array_map( + static fn (Token $token) => $token->getContent(), + $shortTokens, + )); + + return $currentTypeValue === $newTypeValue + ? $type + : new TypeExpression($newTypeValue, null, []); + }); + + return $typeExpression->toString(); + } + + /** + * @param _Uses $uses + */ + private function fixExtendsImplements(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + // We handle `extends` and `implements` with similar logic, but we need to exit the loop under different conditions. + $isExtends = $tokens[$index]->isGivenKind(\T_EXTENDS); + $index = $tokens->getNextMeaningfulToken($index); + + $typeStartIndex = null; + $typeEndIndex = null; + + while (true) { + if ($tokens[$index]->equalsAny([',', '{', [\T_IMPLEMENTS]])) { + if (null !== $typeStartIndex) { + $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName); + } + $typeStartIndex = null; + + if ($tokens[$index]->equalsAny($isExtends ? [[\T_IMPLEMENTS], '{'] : ['{'])) { + break; + } + } else { + if (null === $typeStartIndex) { + $typeStartIndex = $index; + } + $typeEndIndex = $index; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * @param _Uses $uses + */ + private function fixCatch(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $index = $tokens->getNextMeaningfulToken($index); // '(' + $index = $tokens->getNextMeaningfulToken($index); // first part of first exception class to be caught + + $typeStartIndex = null; + $typeEndIndex = null; + + while (true) { + if ($tokens[$index]->equalsAny([')', [\T_VARIABLE], [CT::T_TYPE_ALTERNATION]])) { + if (null === $typeStartIndex) { + break; + } + + $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName); + $typeStartIndex = null; + + if ($tokens[$index]->equals(')')) { + break; + } + } else { + if (null === $typeStartIndex) { + $typeStartIndex = $index; + } + $typeEndIndex = $index; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * @param _Uses $uses + */ + private function fixAttribute(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index); + + foreach ($attributeAnalysis->getAttributes() as $attribute) { + $index = $attribute['start']; + while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + $index = $tokens->getPrevMeaningfulToken($index); + } + $this->fixNextName($tokens, $index, $uses, $namespaceName); + } + } + + /** + * @param _Uses $uses + */ + private function fixPrevName(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $typeStartIndex = null; + $typeEndIndex = null; + + while (true) { + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isObjectOperator()) { + break; + } + + if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + $typeStartIndex = $index; + if (null === $typeEndIndex) { + $typeEndIndex = $index; + } + } else { + if (null !== $typeEndIndex) { + $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName); + } + + break; + } + } + } + + /** + * @param _Uses $uses + */ + private function fixNextName(Tokens $tokens, int $index, array $uses, string $namespaceName): void + { + $typeStartIndex = null; + $typeEndIndex = null; + + while (true) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + if (null === $typeStartIndex) { + $typeStartIndex = $index; + } + $typeEndIndex = $index; + } else { + if (null !== $typeStartIndex) { + $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName); + } + + break; + } + } + } + + /** + * @param _Uses $uses + */ + private function shortenClassIfPossible(Tokens $tokens, int $typeStartIndex, int $typeEndIndex, array $uses, string $namespaceName): int + { + /** @var non-empty-string $content */ + $content = $tokens->generatePartialCode($typeStartIndex, $typeEndIndex); + $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName); + if (null === $newTokens) { + return 0; + } + + $tokens->overrideRange($typeStartIndex, $typeEndIndex, $newTokens); + + return \count($newTokens) - ($typeEndIndex - $typeStartIndex) - 1; + } + + /** + * @param _Uses $uses + */ + private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName): void + { + $typeStartIndex = $type->getStartIndex(); + + if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex); + } + + $types = $this->getTypes($tokens, $typeStartIndex, $type->getEndIndex()); + + foreach ($types as [$startIndex, $endIndex]) { + /** @var non-empty-string $content */ + $content = $tokens->generatePartialCode($startIndex, $endIndex); + $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName); + if (null !== $newTokens) { + $tokens->overrideRange($startIndex, $endIndex, $newTokens); + } + } + } + + /** + * Determines short type based on FQCN, current namespace and imports (`use` declarations). + * + * @param non-empty-string $typeName + * @param _ImportType $importKind + * @param _Uses $uses + * + * @return null|non-empty-list + */ + private function determineShortType(string $typeName, string $importKind, array $uses, string $namespaceName): ?array + { + if (null !== $this->discoveredSymbols) { + if (!$this->isReservedIdentifier($typeName)) { + $this->discoveredSymbols[$importKind][] = $typeName; + } + + return null; + } + + $fqcn = $this->resolveSymbol($typeName, $importKind, $uses, $namespaceName); + $shortenedType = $this->shortenSymbol($fqcn, $importKind, $uses, $namespaceName); + if ($shortenedType === $typeName) { + return null; + } + + return $this->namespacedStringToTokens($shortenedType); + } + + /** + * @return iterable + */ + private function getTypes(Tokens $tokens, int $index, int $endIndex): iterable + { + $skipNextYield = false; + $typeStartIndex = $typeEndIndex = null; + while (true) { + if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) { + $index = $tokens->getNextMeaningfulToken($index); + $typeStartIndex = $typeEndIndex = null; + + continue; + } + + if ( + $tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]) + || $index > $endIndex + ) { + if (!$skipNextYield && null !== $typeStartIndex) { + $origCount = \count($tokens); + + yield [$typeStartIndex, $typeEndIndex]; + + $endIndex += \count($tokens) - $origCount; + + // type tokens were possibly updated, restart type match + $skipNextYield = true; + $index = $typeEndIndex = $typeStartIndex; + } else { + $skipNextYield = false; + $index = $tokens->getNextMeaningfulToken($index); + $typeStartIndex = $typeEndIndex = null; + } + + if ($index > $endIndex) { + break; + } + + continue; + } + + if (null === $typeStartIndex) { + $typeStartIndex = $index; + } + $typeEndIndex = $index; + + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * @return non-empty-list + */ + private function namespacedStringToTokens(string $input): array + { + $tokens = []; + + if (str_starts_with($input, '\\')) { + $tokens[] = new Token([\T_NS_SEPARATOR, '\\']); + $input = substr($input, 1); + } + + $parts = explode('\\', $input); + foreach ($parts as $index => $part) { + $tokens[] = new Token([\T_STRING, $part]); + + if ($index !== \count($parts) - 1) { + $tokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + } + + return $tokens; + } + + private function normalizeFqcn(string $input): string + { + $backslashPosition = strrpos($input, '\\'); + if (false === $backslashPosition) { + return strtolower($input); + } + + $namespacePartEndPosition = $backslashPosition + 1; + $mainPart = substr($input, 0, $namespacePartEndPosition); + $lastPart = substr($input, $namespacePartEndPosition); + + return $mainPart.strtolower($lastPart); + } + + /** + * We need to create import processor dynamically (not in constructor), because actual whitespace configuration + * is set later, not when fixer's instance is created. + */ + private function createImportProcessor(): ImportProcessor + { + return new ImportProcessor($this->whitespacesConfig); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php new file mode 100644 index 0000000..1674869 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php @@ -0,0 +1,733 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Processor\ImportProcessor; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * import_classes?: bool|null, + * import_constants?: bool|null, + * import_functions?: bool|null, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * import_classes: bool|null, + * import_constants: bool|null, + * import_functions: bool|null, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GlobalNamespaceImportFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private ImportProcessor $importProcessor; + + public function __construct() + { + parent::__construct(); + + $this->importProcessor = new ImportProcessor($this->whitespacesConfig); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Imports or fully qualifies global classes/functions/constants.', + [ + new CodeSample( + <<<'PHP' + true, 'import_constants' => true, 'import_functions' => true], + ), + new CodeSample( + <<<'PHP' + false, 'import_constants' => false, 'import_functions' => false], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, OrderedImportsFixer, StatementIndentationFixer. + * Must run after NativeConstantInvocationFixer, NativeFunctionInvocationFixer, StringableForToStringFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_DOC_COMMENT, \T_NS_SEPARATOR, \T_USE]) + && $tokens->isTokenKindFound(\T_NAMESPACE) + && 1 === $tokens->countTokenKind(\T_NAMESPACE) + && $tokens->isMonolithicPhp(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $namespaceAnalyses = $tokens->getNamespaceDeclarations(); + + if (1 !== \count($namespaceAnalyses) || $namespaceAnalyses[0]->isGlobalNamespace()) { + return; + } + + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + $newImports = []; + + if (true === $this->configuration['import_constants']) { + $newImports['const'] = $this->importConstants($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_constants']) { + $this->fullyQualifyConstants($tokens, $useDeclarations); + } + + if (true === $this->configuration['import_functions']) { + $newImports['function'] = $this->importFunctions($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_functions']) { + $this->fullyQualifyFunctions($tokens, $useDeclarations); + } + + if (true === $this->configuration['import_classes']) { + $newImports['class'] = $this->importClasses($tokens, $useDeclarations); + } elseif (false === $this->configuration['import_classes']) { + $this->fullyQualifyClasses($tokens, $useDeclarations); + } + + if (\count($newImports) > 0) { + if (\count($useDeclarations) > 0) { + $useDeclaration = end($useDeclarations); + $atIndex = $useDeclaration->getEndIndex() + 1; + } else { + \assert(isset($tokens->getNamespaceDeclarations()[0])); + $namespace = $tokens->getNamespaceDeclarations()[0]; + $atIndex = $namespace->getEndIndex() + 1; + } + + $this->importProcessor->insertImports($tokens, $newImports, $atIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('import_constants', 'Whether to import, not import or ignore global constants.')) + ->setDefault(null) + ->setAllowedTypes(['null', 'bool']) + ->getOption(), + (new FixerOptionBuilder('import_functions', 'Whether to import, not import or ignore global functions.')) + ->setDefault(null) + ->setAllowedTypes(['null', 'bool']) + ->getOption(), + (new FixerOptionBuilder('import_classes', 'Whether to import, not import or ignore global classes.')) + ->setDefault(true) + ->setAllowedTypes(['null', 'bool']) + ->getOption(), + ]); + } + + /** + * @param list $useDeclarations + * + * @return array + */ + private function importConstants(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant(), true); + + // find namespaced const declarations (`const FOO = 1`) + // and add them to the not importable names (already used) + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isClassy()) { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if (!$token->isGivenKind(\T_CONST)) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + $other[$tokens[$index]->getContent()] = true; + } + + $analyzer = new TokensAnalyzer($tokens); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + $name = $token->getContent(); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isConstantInvocation($index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + // found an unqualified constant invocation + // add it to the not importable names (already used) + $other[$name] = true; + } + + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($nsSeparatorIndex); + if ($tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_STRING])) { + continue; + } + + $indices[] = $index; + } + + return $this->prepareImports($tokens, $indices, $global, $other, true); + } + + /** + * @param list $useDeclarations + * + * @return array + */ + private function importFunctions(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction(), false); + + // find function declarations + // and add them to the not importable names (already used) + foreach ($this->findFunctionDeclarations($tokens, 0, $tokens->count() - 1) as $name) { + $other[strtolower($name)] = true; + } + + $analyzer = new FunctionsAnalyzer(); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + $name = strtolower($token->getContent()); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isGlobalFunctionUsage($tokens, $index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + $other[$name] = true; + } + + continue; + } + + $indices[] = $index; + } + + return $this->prepareImports($tokens, $indices, $global, $other, false); + } + + /** + * @param list $useDeclarations + * + * @return array + */ + private function importClasses(Tokens $tokens, array $useDeclarations): array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass(), false); + + /** @var array $docBlocks */ + $docBlocks = []; + + // find class declarations and class usages in docblocks + // and add them to the not importable names (already used) + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $docBlocks[$index] = new DocBlock($token->getContent()); + + $this->traverseDocBlockTypes($docBlocks[$index], static function (string $type) use ($global, &$other): void { + if (str_contains($type, '\\')) { + return; + } + + $name = strtolower($type); + + if (!isset($global[$name])) { + $other[$name] = true; + } + }); + } + + if (!$token->isClassy()) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(\T_STRING)) { + $other[strtolower($tokens[$index]->getContent())] = true; + } + } + + $analyzer = new ClassyAnalyzer(); + $indices = []; + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + $name = strtolower($token->getContent()); + + if (isset($other[$name])) { + continue; + } + + if (!$analyzer->isClassyInvocation($tokens, $index)) { + continue; + } + + $nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) { + if (!isset($global[$name])) { + $other[$name] = true; + } + + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($nsSeparatorIndex)]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_STRING])) { + continue; + } + + $indices[] = $index; + } + + $imports = []; + + foreach ($docBlocks as $index => $docBlock) { + $changed = $this->traverseDocBlockTypes($docBlock, static function (string $type) use ($global, $other, &$imports): string { + if ('\\' !== $type[0]) { + return $type; + } + + /** @var non-empty-string $name */ + $name = substr($type, 1); + + $checkName = strtolower($name); + + if (str_contains($checkName, '\\') || isset($other[$checkName])) { + return $type; + } + + if (isset($global[$checkName])) { + return \is_string($global[$checkName]) ? $global[$checkName] : $name; + } + + $imports[$checkName] = $name; + + return $name; + }); + + if ($changed) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]); + } + } + + return array_merge($imports, $this->prepareImports($tokens, $indices, $global, $other, false)); + } + + /** + * Removes the leading slash at the given indices (when the name is not already used). + * + * @param list $indices + * @param array $global + * @param array $other + * + * @return array array keys contain the names that must be imported + */ + private function prepareImports(Tokens $tokens, array $indices, array $global, array $other, bool $caseSensitive): array + { + $imports = []; + + foreach ($indices as $index) { + /** @var non-empty-string $name */ + $name = $tokens[$index]->getContent(); + $checkName = $caseSensitive ? $name : strtolower($name); + + if (isset($other[$checkName])) { + continue; + } + + if (!isset($global[$checkName])) { + $imports[$checkName] = $name; + } elseif (\is_string($global[$checkName])) { + $tokens[$index] = new Token([\T_STRING, $global[$checkName]]); + } + + $tokens->clearAt($tokens->getPrevMeaningfulToken($index)); + } + + return $imports; + } + + /** + * @param list $useDeclarations + */ + private function fullyQualifyConstants(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(CT::T_CONST_IMPORT)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant() && !$declaration->isAliased(), true); + + if ([] === $global) { + return; + } + + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + if (!isset($global[$token->getContent()])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isConstantInvocation($index)) { + continue; + } + + $tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param list $useDeclarations + */ + private function fullyQualifyFunctions(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction() && !$declaration->isAliased(), false); + + if ([] === $global) { + return; + } + + $analyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + if (!isset($global[strtolower($token->getContent())])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isGlobalFunctionUsage($tokens, $index)) { + continue; + } + + $tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param list $useDeclarations + */ + private function fullyQualifyClasses(Tokens $tokens, array $useDeclarations): void + { + if (!$tokens->isTokenKindFound(\T_USE)) { + return; + } + + [$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass() && !$declaration->isAliased(), false); + + if ([] === $global) { + return; + } + + $analyzer = new ClassyAnalyzer(); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $doc = new DocBlock($token->getContent()); + + $changed = $this->traverseDocBlockTypes($doc, static function (string $type) use ($global): string { + if (!isset($global[strtolower($type)])) { + return $type; + } + + return '\\'.$type; + }); + + if ($changed) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + + continue; + } + + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + + if (!isset($global[strtolower($token->getContent())])) { + continue; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + + if (!$analyzer->isClassyInvocation($tokens, $index)) { + continue; + } + + $tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\'])); + } + } + + /** + * @param list $declarations + * + * @return array{0: array, 1: array} + */ + private function filterUseDeclarations(array $declarations, callable $callback, bool $caseSensitive): array + { + $global = []; + $other = []; + + foreach ($declarations as $declaration) { + if (!$callback($declaration)) { + continue; + } + + $fullName = ltrim($declaration->getFullName(), '\\'); + + if (str_contains($fullName, '\\')) { + $name = $caseSensitive ? $declaration->getShortName() : strtolower($declaration->getShortName()); + $other[$name] = true; + + continue; + } + + $checkName = $caseSensitive ? $fullName : strtolower($fullName); + $alias = $declaration->getShortName(); + $global[$checkName] = $alias === $fullName ? true : $alias; + } + + return [$global, $other]; + } + + /** + * @return iterable + */ + private function findFunctionDeclarations(Tokens $tokens, int $start, int $end): iterable + { + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ($token->isClassy()) { + $classStart = $tokens->getNextTokenOfKind($index, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classStart); + + for ($index = $classStart; $index <= $classEnd; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $methodStart = $tokens->getNextTokenOfKind($index, ['{', ';']); + + if ($tokens[$methodStart]->equals(';')) { + $index = $methodStart; + + continue; + } + + $methodEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $methodStart); + + foreach ($this->findFunctionDeclarations($tokens, $methodStart, $methodEnd) as $function) { + yield $function; + } + + $index = $methodEnd; + } + + continue; + } + + if (!$token->isGivenKind(\T_FUNCTION)) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind(\T_STRING)) { + yield $tokens[$index]->getContent(); + } + } + } + + private function traverseDocBlockTypes(DocBlock $doc, callable $callback): bool + { + $annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES); + + if (0 === \count($annotations)) { + return false; + } + + $changed = false; + + foreach ($annotations as $annotation) { + $types = $annotation->getTypes(); + + $new = array_map(static function (string $fullType) use ($callback): string { + Preg::matchAll('/[\\\\\w]+(?![\\\\\w:])/', $fullType, $matches, \PREG_OFFSET_CAPTURE); + + foreach (array_reverse($matches[0]) as [$type, $offset]) { + $newType = $callback($type); + + if (null !== $newType && $type !== $newType) { + $fullType = substr_replace($fullType, $newType, $offset, \strlen($type)); + } + } + + return $fullType; + }, $types); + + if ($types !== $new) { + $annotation->setTypes($new); + $changed = true; + } + } + + return $changed; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php new file mode 100644 index 0000000..5c6e102 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php @@ -0,0 +1,371 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * group_types?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * group_types: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Volodymyr Kupriienko + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GroupImportFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @internal */ + public const GROUP_CLASSY = 'classy'; + + /** @internal */ + public const GROUP_CONSTANTS = 'constants'; + + /** @internal */ + public const GROUP_FUNCTIONS = 'functions'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be group use for the same namespaces.', + [ + new CodeSample( + " [self::GROUP_CLASSY]], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_USE); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowedTypes = [self::GROUP_CLASSY, self::GROUP_FUNCTIONS, self::GROUP_CONSTANTS]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('group_types', 'Defines the order of import types.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([static function (array $types) use ($allowedTypes): bool { + foreach ($types as $type) { + if (!\in_array($type, $allowedTypes, true)) { + throw new InvalidOptionsException( + \sprintf( + 'Invalid group type: %s, allowed types: %s.', + $type, + Utils::naturalLanguageJoin($allowedTypes), + ), + ); + } + } + + return true; + }]) + ->setDefault($allowedTypes) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useWithSameNamespaces = $this->getSameNamespacesByType($tokens); + + if ([] === $useWithSameNamespaces) { + return; + } + + $typeMap = [ + NamespaceUseAnalysis::TYPE_CLASS => self::GROUP_CLASSY, + NamespaceUseAnalysis::TYPE_FUNCTION => self::GROUP_FUNCTIONS, + NamespaceUseAnalysis::TYPE_CONSTANT => self::GROUP_CONSTANTS, + ]; + + // As a first step we need to remove all the use statements for the enabled import types. + // We can't add new group imports yet, because we need to operate on previously determined token indices for all types. + foreach ($useWithSameNamespaces as $type => $uses) { + if (!\in_array($typeMap[$type], $this->configuration['group_types'], true)) { + continue; + } + + $this->removeSingleUseStatements($uses, $tokens); + } + + foreach ($useWithSameNamespaces as $type => $uses) { + if (!\in_array($typeMap[$type], $this->configuration['group_types'], true)) { + continue; + } + + $this->addGroupUseStatements($uses, $tokens); + } + } + + /** + * Gets namespace use analyzers with same namespaces. + * + * @return array> + */ + private function getSameNamespacesByType(Tokens $tokens): array + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + + if (0 === \count($useDeclarations)) { + return []; + } + + $allNamespaceAndType = array_map( + fn (NamespaceUseAnalysis $useDeclaration): string => $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType(), + $useDeclarations, + ); + + $sameNamespaces = array_filter(array_count_values($allNamespaceAndType), static fn (int $count): bool => $count > 1); + $sameNamespaces = array_keys($sameNamespaces); + + $sameNamespaceAnalysis = array_filter($useDeclarations, function (NamespaceUseAnalysis $useDeclaration) use ($sameNamespaces): bool { + $namespaceNameAndType = $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType(); + + return \in_array($namespaceNameAndType, $sameNamespaces, true); + }); + + usort($sameNamespaceAnalysis, function (NamespaceUseAnalysis $a, NamespaceUseAnalysis $b): int { + $namespaceA = $this->getNamespaceNameWithSlash($a); + $namespaceB = $this->getNamespaceNameWithSlash($b); + + $namespaceDifference = \strlen($namespaceA) <=> \strlen($namespaceB); + + return 0 !== $namespaceDifference ? $namespaceDifference : $a->getFullName() <=> $b->getFullName(); + }); + + $sameNamespaceAnalysisByType = []; + foreach ($sameNamespaceAnalysis as $analysis) { + $sameNamespaceAnalysisByType[$analysis->getType()][] = $analysis; + } + + ksort($sameNamespaceAnalysisByType); + + return $sameNamespaceAnalysisByType; + } + + /** + * @param list $statements + */ + private function removeSingleUseStatements(array $statements, Tokens $tokens): void + { + foreach ($statements as $useDeclaration) { + $index = $useDeclaration->getStartIndex(); + $endIndex = $useDeclaration->getEndIndex(); + + $useStatementTokens = [\T_USE, \T_WHITESPACE, \T_STRING, \T_NS_SEPARATOR, \T_AS, CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; + + while ($index !== $endIndex) { + if ($tokens[$index]->isGivenKind($useStatementTokens)) { + $tokens->clearAt($index); + } + + ++$index; + } + + if (isset($tokens[$index]) && $tokens[$index]->equals(';')) { + $tokens->clearAt($index); + } + + ++$index; + + if (isset($tokens[$index]) && $tokens[$index]->isGivenKind(\T_WHITESPACE)) { + $tokens->clearAt($index); + } + } + } + + /** + * @param non-empty-list $statements + */ + private function addGroupUseStatements(array $statements, Tokens $tokens): void + { + $currentUseDeclaration = null; + $insertIndex = $statements[0]->getStartIndex(); + + // If group import was inserted in place of removed imports, it may have more tokens than before, + // and indices stored in imports of another type can be out-of-sync, and can point in the middle of group import. + // Let's move the pointer to the closest empty token (erased single import). + if (null !== $tokens[$insertIndex]->getId() || '' !== $tokens[$insertIndex]->getContent()) { + do { + ++$insertIndex; + } while (null !== $tokens[$insertIndex]->getId() || '' !== $tokens[$insertIndex]->getContent()); + } + + foreach ($statements as $index => $useDeclaration) { + if ($this->areDeclarationsDifferent($currentUseDeclaration, $useDeclaration)) { + $currentUseDeclaration = $useDeclaration; + $insertIndex += $this->createNewGroup( + $tokens, + $insertIndex, + $useDeclaration, + rtrim($this->getNamespaceNameWithSlash($currentUseDeclaration), '\\'), + ); + } else { + $newTokens = [ + new Token(','), + new Token([\T_WHITESPACE, ' ']), + ]; + + if ($useDeclaration->isAliased()) { + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + $newTokens = []; + + $insertIndex += $this->insertToGroupUseWithAlias($tokens, $insertIndex, $useDeclaration); + } + + $newTokens[] = new Token([\T_STRING, $useDeclaration->getShortName()]); + + if (!isset($statements[$index + 1]) || $this->areDeclarationsDifferent($currentUseDeclaration, $statements[$index + 1])) { + $newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + $newTokens[] = new Token(';'); + $newTokens[] = new Token([\T_WHITESPACE, "\n"]); + } + + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + } + } + } + + private function getNamespaceNameWithSlash(NamespaceUseAnalysis $useDeclaration): string + { + $position = strrpos($useDeclaration->getFullName(), '\\'); + if (false === $position || 0 === $position) { + return $useDeclaration->getFullName(); + } + + return substr($useDeclaration->getFullName(), 0, $position + 1); + } + + /** + * Insert use with alias to the group. + */ + private function insertToGroupUseWithAlias(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration): int + { + $newTokens = [ + new Token([\T_STRING, substr($useDeclaration->getFullName(), (int) strripos($useDeclaration->getFullName(), '\\') + 1)]), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_AS, 'as']), + new Token([\T_WHITESPACE, ' ']), + ]; + + $tokens->insertAt($insertIndex, $newTokens); + + return \count($newTokens); + } + + /** + * Creates new use statement group. + */ + private function createNewGroup(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration, string $currentNamespace): int + { + $insertedTokens = 0; + + $newTokens = [ + new Token([\T_USE, 'use']), + new Token([\T_WHITESPACE, ' ']), + ]; + + if ($useDeclaration->isFunction() || $useDeclaration->isConstant()) { + $importStatementParams = $useDeclaration->isFunction() + ? [CT::T_FUNCTION_IMPORT, 'function'] + : [CT::T_CONST_IMPORT, 'const']; + + $newTokens[] = new Token($importStatementParams); + $newTokens[] = new Token([\T_WHITESPACE, ' ']); + } + + $namespaceParts = explode('\\', $currentNamespace); + + foreach ($namespaceParts as $part) { + $newTokens[] = new Token([\T_STRING, $part]); + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); + + $newTokensCount = \count($newTokens); + $tokens->insertAt($insertIndex, $newTokens); + $insertedTokens += $newTokensCount; + + $insertIndex += $newTokensCount; + + if ($useDeclaration->isAliased()) { + $inserted = $this->insertToGroupUseWithAlias($tokens, $insertIndex + 1, $useDeclaration) + 1; + $insertedTokens += $inserted; + $insertIndex += $inserted; + } + + $tokens->insertAt($insertIndex, new Token([\T_STRING, $useDeclaration->getShortName()])); + + return ++$insertedTokens; + } + + /** + * Check if namespace use analyses are different. + */ + private function areDeclarationsDifferent(?NamespaceUseAnalysis $analysis1, ?NamespaceUseAnalysis $analysis2): bool + { + if (null === $analysis1 || null === $analysis2) { + return true; + } + + $namespaceName1 = $this->getNamespaceNameWithSlash($analysis1); + $namespaceName2 = $this->getNamespaceNameWithSlash($analysis2); + + return $namespaceName1 !== $namespaceName2 || $analysis1->getType() !== $analysis2->getType(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php new file mode 100644 index 0000000..97ae242 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Carlos Cirello + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoLeadingImportSlashFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove leading slashes in `use` clauses.', + [new CodeSample("isTokenKindFound(\T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $usesIndices = $tokensAnalyzer->getImportUseIndexes(); + + foreach ($usesIndices as $idx) { + $nextTokenIdx = $tokens->getNextMeaningfulToken($idx); + $nextToken = $tokens[$nextTokenIdx]; + + if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) { + $this->removeLeadingImportSlash($tokens, $nextTokenIdx); + } elseif ($nextToken->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { + $nextTokenIdx = $tokens->getNextMeaningfulToken($nextTokenIdx); + if ($tokens[$nextTokenIdx]->isGivenKind(\T_NS_SEPARATOR)) { + $this->removeLeadingImportSlash($tokens, $nextTokenIdx); + } + } + } + } + + private function removeLeadingImportSlash(Tokens $tokens, int $index): void + { + $previousIndex = $tokens->getPrevNonWhitespace($index); + + if ( + $previousIndex < $index - 1 + || $tokens[$previousIndex]->isComment() + ) { + $tokens->clearAt($index); + + return; + } + + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php new file mode 100644 index 0000000..6dac26a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnneededImportAliasFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Imports should not be aliased as the same name.', + [new CodeSample("isAllTokenKindsFound([\T_USE, \T_AS]); + } + + /** + * {@inheritdoc} + * + * Must run before NoSinglelineWhitespaceBeforeSemicolonsFixer. + * Must run after PhpUnitNamespacedFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_AS)) { + continue; + } + + $aliasIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$aliasIndex]->isGivenKind(\T_STRING)) { + continue; + } + + $importIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$importIndex]->isGivenKind(\T_STRING)) { + continue; + } + + if ($tokens[$importIndex]->getContent() !== $tokens[$aliasIndex]->getContent()) { + continue; + } + + do { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } while ($tokens[$importIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING, \T_AS]) || $tokens[$importIndex]->equals(',')); + + if ($tokens[$importIndex]->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } + + if (!$tokens[$importIndex]->isGivenKind([\T_USE, CT::T_GROUP_IMPORT_BRACE_OPEN])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($aliasIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php new file mode 100644 index 0000000..3b855c8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php @@ -0,0 +1,456 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnusedImportsFixer extends AbstractFixer +{ + private const TOKENS_NOT_BEFORE_FUNCTION_CALL = [\T_NEW, FCT::T_ATTRIBUTE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Unused `use` statements must be removed.', + [new CodeSample("isTokenKindFound(\T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens, true); + + if (0 === \count($useDeclarations)) { + return; + } + + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $currentNamespaceUseDeclarations = []; + $currentNamespaceUseDeclarationIndices = []; + + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->getStartIndex() >= $namespace->getScopeStartIndex() && $useDeclaration->getEndIndex() <= $namespace->getScopeEndIndex()) { + $currentNamespaceUseDeclarations[] = $useDeclaration; + $currentNamespaceUseDeclarationIndices[$useDeclaration->getStartIndex()] = $useDeclaration->getEndIndex(); + } + } + + foreach ($currentNamespaceUseDeclarations as $useDeclaration) { + if (!$this->isImportUsed($tokens, $namespace, $useDeclaration, $currentNamespaceUseDeclarationIndices)) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + + $this->removeUsesInSameNamespace($tokens, $currentNamespaceUseDeclarations, $namespace); + } + } + + /** + * @param array $ignoredIndices indices of the use statements themselves that should not be checked as being "used" + */ + private function isImportUsed(Tokens $tokens, NamespaceAnalysis $namespace, NamespaceUseAnalysis $import, array $ignoredIndices): bool + { + $analyzer = new TokensAnalyzer($tokens); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + + $namespaceEndIndex = $namespace->getScopeEndIndex(); + $inAttribute = false; + + for ($index = $namespace->getScopeStartIndex(); $index <= $namespaceEndIndex; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $inAttribute = true; + + continue; + } + + if ($token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $inAttribute = false; + + continue; + } + + if (isset($ignoredIndices[$index])) { + $index = $ignoredIndices[$index]; + + continue; + } + + if ($token->isGivenKind(\T_STRING)) { + if (0 !== strcasecmp($import->getShortName(), $token->getContent())) { + continue; + } + + $prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if ($prevMeaningfulToken->isGivenKind(\T_NAMESPACE)) { + $index = $tokens->getNextTokenOfKind($index, [';', '{', [\T_CLOSE_TAG]]); + + continue; + } + + if ( + $prevMeaningfulToken->isGivenKind([\T_NS_SEPARATOR, \T_FUNCTION, \T_DOUBLE_COLON]) + || $prevMeaningfulToken->isObjectOperator() + ) { + continue; + } + + if ($prevMeaningfulToken->isGivenKind(\T_CONST) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('=')) { + continue; + } + + if ($inAttribute) { + return true; + } + + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index); + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $nextMeaningfulIndex)) { + continue; + } + + $nextMeaningfulToken = $tokens[$nextMeaningfulIndex]; + + if ($analyzer->isConstantInvocation($index)) { + $type = NamespaceUseAnalysis::TYPE_CONSTANT; + } elseif ($nextMeaningfulToken->equals('(') && !$prevMeaningfulToken->isGivenKind(self::TOKENS_NOT_BEFORE_FUNCTION_CALL)) { + $type = NamespaceUseAnalysis::TYPE_FUNCTION; + } else { + $type = NamespaceUseAnalysis::TYPE_CLASS; + } + + if ($import->getType() === $type) { + return true; + } + + continue; + } + + if ($token->isComment() + && Preg::match( + '/(?getShortName().'(?![[:alnum:]_])/i', + $token->getContent(), + ) + ) { + return true; + } + } + + return false; + } + + private function removeUseDeclaration( + Tokens $tokens, + NamespaceUseAnalysis $useDeclaration, + bool $forceCompleteRemoval = false + ): void { + [$start, $end] = ($useDeclaration->isInMulti() && !$forceCompleteRemoval) + ? [$useDeclaration->getChunkStartIndex(), $useDeclaration->getChunkEndIndex()] + : [$useDeclaration->getStartIndex(), $useDeclaration->getEndIndex()]; + $loopStartIndex = $useDeclaration->isInMulti() || $forceCompleteRemoval ? $end : $end - 1; + + for ($index = $loopStartIndex; $index >= $start; --$index) { + if ($tokens[$index]->isComment()) { + continue; + } + + if (!$tokens[$index]->isWhitespace() || !str_contains($tokens[$index]->getContent(), "\n")) { + $tokens->clearAt($index); + + continue; + } + + // when multi line white space keep the line feed if the previous token is a comment + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$prevIndex]->isComment()) { + $content = $tokens[$index]->getContent(); + $tokens[$index] = new Token([\T_WHITESPACE, substr($content, strrpos($content, "\n"))]); // preserve indent only + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + // For multi-use import statements the tokens containing FQN were already removed in the loop above. + // We need to clean up tokens around the ex-chunk to keep the correct syntax and achieve proper formatting. + if (!$forceCompleteRemoval && $useDeclaration->isInMulti()) { + $this->cleanUpAfterImportChunkRemoval($tokens, $useDeclaration); + + return; + } + + if ($tokens[$useDeclaration->getEndIndex()]->equals(';')) { // do not remove `? >` + $tokens->clearAt($useDeclaration->getEndIndex()); + } + + $this->cleanUpSurroundingNewLines($tokens, $useDeclaration); + } + + /** + * @param list $useDeclarations + */ + private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, NamespaceAnalysis $namespaceDeclaration): void + { + $namespace = $namespaceDeclaration->getFullName(); + $nsLength = \strlen($namespace.'\\'); + + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->isAliased()) { + continue; + } + + $useDeclarationFullName = ltrim($useDeclaration->getFullName(), '\\'); + + if (!str_starts_with($useDeclarationFullName, $namespace.'\\')) { + continue; + } + + $partName = substr($useDeclarationFullName, $nsLength); + + if (!str_contains($partName, '\\')) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + } + + private function cleanUpAfterImportChunkRemoval(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void + { + $beforeChunkIndex = $tokens->getPrevMeaningfulToken($useDeclaration->getChunkStartIndex()); + $afterChunkIndex = $tokens->getNextMeaningfulToken($useDeclaration->getChunkEndIndex()); + $hasNonEmptyTokenBefore = $this->scanForNonEmptyTokensUntilNewLineFound( + $tokens, + $afterChunkIndex, + -1, + ); + $hasNonEmptyTokenAfter = $this->scanForNonEmptyTokensUntilNewLineFound( + $tokens, + $afterChunkIndex, + 1, + ); + + // We don't want to merge consequent new lines with indentation (leading to e.g. `\n \n `), + // so it's safe to merge whitespace only if there is any non-empty token before or after the chunk. + $mergingSurroundingWhitespaceIsSafe = $hasNonEmptyTokenBefore[1] || $hasNonEmptyTokenAfter[1]; + $clearToken = static function (int $index) use ($tokens, $mergingSurroundingWhitespaceIsSafe): void { + if ($mergingSurroundingWhitespaceIsSafe) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens->clearAt($index); + } + }; + + if ($tokens[$afterChunkIndex]->equals(',')) { + $clearToken($afterChunkIndex); + } elseif ($tokens[$beforeChunkIndex]->equals(',')) { + $clearToken($beforeChunkIndex); + } + + // Ensure there's a single space where applicable, otherwise no space (before comma, before closing brace) + for ($index = $beforeChunkIndex; $index <= $afterChunkIndex; ++$index) { + if (null === $tokens[$index]->getId() || !$tokens[$index]->isWhitespace(' ')) { + continue; + } + + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + if ( + $tokens[$nextTokenIndex]->equals(',') + || $tokens[$nextTokenIndex]->equals(';') + || $tokens[$nextTokenIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE) + ) { + $tokens->clearAt($index); + } else { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevTokenIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $tokens->clearAt($index); + } + } + + $this->removeLineIfEmpty($tokens, $useDeclaration); + $this->removeImportStatementIfEmpty($tokens, $useDeclaration); + } + + private function cleanUpSurroundingNewLines(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void + { + $prevIndex = $useDeclaration->getStartIndex() - 1; + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isWhitespace()) { + $content = rtrim($prevToken->getContent(), " \t"); + + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content); + + $prevToken = $tokens[$prevIndex]; + } + + if (!isset($tokens[$useDeclaration->getEndIndex() + 1])) { + return; + } + + $nextIndex = $tokens->getNonEmptySibling($useDeclaration->getEndIndex(), 1); + + if (null === $nextIndex) { + return; + } + + $nextToken = $tokens[$nextIndex]; + + if ($nextToken->isWhitespace()) { + $content = Preg::replace( + "#^\r\n|^\n#", + '', + ltrim($nextToken->getContent(), " \t"), + 1, + ); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + + $nextToken = $tokens[$nextIndex]; + } + + if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) { + $content = $prevToken->getContent().$nextToken->getContent(); + + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + + $tokens->clearAt($prevIndex); + } + } + + private function removeImportStatementIfEmpty(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void + { + // First we look for empty groups where all chunks were removed (`use Foo\{};`). + // We're only interested in ending brace if its index is between start and end of the import statement. + $endingBraceIndex = $tokens->getPrevTokenOfKind( + $useDeclaration->getEndIndex(), + [[CT::T_GROUP_IMPORT_BRACE_CLOSE]], + ); + + if ($endingBraceIndex > $useDeclaration->getStartIndex()) { + $openingBraceIndex = $tokens->getPrevMeaningfulToken($endingBraceIndex); + + if ($tokens[$openingBraceIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $this->removeUseDeclaration($tokens, $useDeclaration, true); + } + } + + // Second we look for empty groups where all comma-separated chunks were removed (`use;`). + $beforeSemicolonIndex = $tokens->getPrevMeaningfulToken($useDeclaration->getEndIndex()); + if ( + $tokens[$beforeSemicolonIndex]->isGivenKind(\T_USE) + || \in_array($tokens[$beforeSemicolonIndex]->getContent(), ['function', 'const'], true) + ) { + $this->removeUseDeclaration($tokens, $useDeclaration, true); + } + } + + private function removeLineIfEmpty(Tokens $tokens, NamespaceUseAnalysis $useAnalysis): void + { + if (!$useAnalysis->isInMulti()) { + return; + } + + $hasNonEmptyTokenBefore = $this->scanForNonEmptyTokensUntilNewLineFound( + $tokens, + $useAnalysis->getChunkStartIndex(), + -1, + ); + $hasNonEmptyTokenAfter = $this->scanForNonEmptyTokensUntilNewLineFound( + $tokens, + $useAnalysis->getChunkEndIndex(), + 1, + ); + + if ( + \is_int($hasNonEmptyTokenBefore[0]) + && !$hasNonEmptyTokenBefore[1] + && \is_int($hasNonEmptyTokenAfter[0]) + && !$hasNonEmptyTokenAfter[1] + ) { + $tokens->clearRange($hasNonEmptyTokenBefore[0], $hasNonEmptyTokenAfter[0] - 1); + } + } + + /** + * Returns tuple with the index of first token with whitespace containing new line char + * and a flag if any non-empty token was found along the way. + * + * @param -1|1 $direction + * + * @return array{0: null|int, 1: bool} + */ + private function scanForNonEmptyTokensUntilNewLineFound(Tokens $tokens, int $index, int $direction): array + { + $hasNonEmptyToken = false; + $newLineTokenIndex = null; + + // Iterate until we find new line OR we get out of $tokens bounds (next sibling index is `null`). + while (\is_int($index)) { + $index = $tokens->getNonEmptySibling($index, $direction); + + if (null === $index || null === $tokens[$index]->getId()) { + continue; + } + + if (!$tokens[$index]->isWhitespace()) { + $hasNonEmptyToken = true; + } elseif (str_starts_with($tokens[$index]->getContent(), "\n")) { + $newLineTokenIndex = $index; + + break; + } + } + + return [$newLineTokenIndex, $hasNonEmptyToken]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php new file mode 100644 index 0000000..74bf01e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php @@ -0,0 +1,659 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Console\Application; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _UseImportInfo array{ + * namespace: non-empty-string, + * startIndex: int, + * endIndex: int, + * importType: self::IMPORT_TYPE_*, + * group: bool, + * } + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * imports_order?: list|null, + * sort_algorithm?: 'alpha'|'length'|'none', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * imports_order: list|null, + * sort_algorithm: 'alpha'|'length'|'none', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Darius Matulionis + * @author Adriano Pilger + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OrderedImportsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const IMPORT_TYPE_CLASS = 'class'; + + /** + * @internal + */ + public const IMPORT_TYPE_CONST = 'const'; + + /** + * @internal + */ + public const IMPORT_TYPE_FUNCTION = 'function'; + + /** + * @internal + */ + public const SORT_ALPHA = 'alpha'; + + /** + * @TODO 4.0 remove the possibility to sort by length + * + * @internal + */ + public const SORT_LENGTH = 'length'; + + /** + * @internal + */ + public const SORT_NONE = 'none'; + + /** + * Array of supported sort types in configuration. + * + * @var non-empty-list + */ + private const SUPPORTED_SORT_TYPES = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION]; + + /** + * Array of supported sort algorithms in configuration. + * + * @var non-empty-list + */ + private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ordering `use` statements.', + [ + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + self::SORT_LENGTH], + ), + new CodeSample( + <<<'PHP' + self::SORT_LENGTH, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ], + ), + new CodeSample( + <<<'PHP' + self::SORT_ALPHA, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ], + ), + new CodeSample( + <<<'PHP' + self::SORT_NONE, + 'imports_order' => [ + self::IMPORT_TYPE_CONST, + self::IMPORT_TYPE_CLASS, + self::IMPORT_TYPE_FUNCTION, + ], + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBetweenImportGroupsFixer. + * Must run after FullyQualifiedStrictTypesFixer, GlobalNamespaceImportFixer, NoLeadingImportSlashFixer. + */ + public function getPriority(): int + { + return -30; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); + + foreach (array_reverse($namespacesImports) as $usesPerNamespaceIndices) { + $count = \count($usesPerNamespaceIndices); + + if (1 === $count) { + $this->setNewOrder($tokens, $this->getNewOrder($usesPerNamespaceIndices, $tokens)); + + continue; + } + + $groupUsesOffset = 0; + $groupUses = [$groupUsesOffset => [$usesPerNamespaceIndices[0]]]; + + // if there's some logic between two `use` statements, sort only imports grouped before that logic + for ($index = 0; $index < $count - 1; ++$index) { + \assert(isset($usesPerNamespaceIndices[$index])); + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [';', [\T_CLOSE_TAG]]); + + if ($tokens[$nextGroupUse]->isGivenKind(\T_CLOSE_TAG)) { + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [[\T_OPEN_TAG]]); + } + + $nextGroupUse = $tokens->getNextMeaningfulToken($nextGroupUse); + + \assert(isset($usesPerNamespaceIndices[$index + 1])); + if ($nextGroupUse !== $usesPerNamespaceIndices[$index + 1]) { + $groupUses[++$groupUsesOffset] = []; + } + + $groupUses[$groupUsesOffset][] = $usesPerNamespaceIndices[$index + 1]; + } + + for ($index = $groupUsesOffset; $index >= 0; --$index) { + \assert(isset($groupUses[$index])); + $this->setNewOrder($tokens, $this->getNewOrder($groupUses[$index], $tokens)); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $supportedSortTypes = self::SUPPORTED_SORT_TYPES; + $fixerName = $this->getName(); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'Whether the statements should be sorted alphabetically or by length (*deprecated*), or not sorted.')) // @TODO 4.0 drop 'length' + ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) + ->setDefault(self::SORT_ALPHA) + ->setNormalizer(static function (Options $options, ?string $value) use ($fixerName): ?string { + if (self::SORT_LENGTH === $value) { + Future::triggerDeprecation(new InvalidFixerConfigurationException($fixerName, \sprintf( + 'Option "sort_algorithm:%s" is deprecated and will be removed in version %d.0.', + self::SORT_LENGTH, + Application::getMajorVersion() + 1, + ))); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('imports_order', 'Defines the order of import types.')) + ->setAllowedTypes(['string[]', 'null']) + ->setAllowedValues([static function (?array $value) use ($supportedSortTypes): bool { + if (null !== $value) { + $missing = array_diff($supportedSortTypes, $value); + if (\count($missing) > 0) { + throw new InvalidOptionsException(\sprintf( + 'Missing sort %s %s.', + 1 === \count($missing) ? 'type' : 'types', + Utils::naturalLanguageJoin(array_values($missing)), + )); + } + + $unknown = array_diff($value, $supportedSortTypes); + if (\count($unknown) > 0) { + throw new InvalidOptionsException(\sprintf( + 'Unknown sort %s %s.', + 1 === \count($unknown) ? 'type' : 'types', + Utils::naturalLanguageJoin(array_values($unknown)), + )); + } + } + + return true; + }]) + ->setDefault( + Future::getV4OrV3(['class', 'function', 'const'], null), + ) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * This method is used for sorting the uses in a namespace. + * + * @param _UseImportInfo $first + * @param _UseImportInfo $second + */ + private function sortAlphabetically(array $first, array $second): int + { + // Replace backslashes by spaces and remove opening braces before sorting for correct sort order + $firstNamespace = str_replace(['\\', '{'], [' ', ''], $this->prepareNamespace($first['namespace'])); + $secondNamespace = str_replace(['\\', '{'], [' ', ''], $this->prepareNamespace($second['namespace'])); + + return true === $this->configuration['case_sensitive'] + ? $firstNamespace <=> $secondNamespace + : strcasecmp($firstNamespace, $secondNamespace); + } + + /** + * This method is used for sorting the uses statements in a namespace by length. + * + * @param _UseImportInfo $first + * @param _UseImportInfo $second + */ + private function sortByLength(array $first, array $second): int + { + $firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']); + $secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']); + + $firstNamespaceLength = \strlen($firstNamespace); + $secondNamespaceLength = \strlen($secondNamespace); + + if ($firstNamespaceLength === $secondNamespaceLength) { + $sortResult = true === $this->configuration['case_sensitive'] + ? $firstNamespace <=> $secondNamespace + : strcasecmp($firstNamespace, $secondNamespace); + } else { + $sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1; + } + + return $sortResult; + } + + private function prepareNamespace(string $namespace): string + { + return trim(Preg::replace('%/\*(.*)\*/%s', '', $namespace)); + } + + /** + * @param list $uses + * + * @return array + */ + private function getNewOrder(array $uses, Tokens $tokens): array + { + $indices = []; + $originalIndices = []; + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $usesCount = \count($uses); + + for ($i = 0; $i < $usesCount; ++$i) { + \assert(isset($uses[$i])); + $index = $uses[$i]; + + $startIndex = $tokens->getTokenNotOfKindsSibling($index + 1, 1, [\T_WHITESPACE]); + \assert(\is_int($startIndex)); + + $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [\T_CLOSE_TAG]]); + $previous = $tokens->getPrevMeaningfulToken($endIndex); + + $group = $tokens[$previous]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE); + if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $type = self::IMPORT_TYPE_CONST; + $index = $tokens->getNextNonWhitespace($startIndex); + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = self::IMPORT_TYPE_FUNCTION; + $index = $tokens->getNextNonWhitespace($startIndex); + } else { + $type = self::IMPORT_TYPE_CLASS; + $index = $startIndex; + } + + $namespaceTokens = []; + + while ($index <= $endIndex) { + $token = $tokens[$index]; + + if ($index === $endIndex || (!$group && $token->equals(','))) { + if ($group && self::SORT_NONE !== $this->configuration['sort_algorithm']) { + // if group import, sort the items within the group definition + + // figure out where the list of namespace parts within the group def. starts + $namespaceTokensCount = \count($namespaceTokens) - 1; + $namespace = ''; + for ($k = 0; $k < $namespaceTokensCount; ++$k) { + \assert(isset($namespaceTokens[$k])); + if ($namespaceTokens[$k]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $namespace .= '{'; + + break; + } + + $namespace .= $namespaceTokens[$k]->getContent(); + } + + // fetch all parts, split up in an array of strings, move comments to the end + $parts = []; + $firstIndent = ''; + $separator = ', '; + $lastIndent = ''; + $hasGroupTrailingComma = false; + + for ($k1 = $k + 1; $k1 < $namespaceTokensCount; ++$k1) { + $comment = ''; + $namespacePart = ''; + for ($k2 = $k1;; ++$k2) { + \assert(isset($namespaceTokens[$k2])); + if ($namespaceTokens[$k2]->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { + break; + } + + if ($namespaceTokens[$k2]->isComment()) { + $comment .= $namespaceTokens[$k2]->getContent(); + + continue; + } + + // if there is any line ending inside the group import, it should be indented properly + if ( + '' === $firstIndent + && $namespaceTokens[$k2]->isWhitespace() + && str_contains($namespaceTokens[$k2]->getContent(), $lineEnding) + ) { + $lastIndent = $lineEnding; + $firstIndent = $lineEnding.$this->whitespacesConfig->getIndent(); + $separator = ','.$firstIndent; + } + + $namespacePart .= $namespaceTokens[$k2]->getContent(); + } + + $namespacePart = trim($namespacePart); + if ('' === $namespacePart) { + $hasGroupTrailingComma = true; + + continue; + } + + $comment = trim($comment); + if ('' !== $comment) { + $namespacePart .= ' '.$comment; + } + + $parts[] = $namespacePart; + + $k1 = $k2; + } + + $sortedParts = $parts; + sort($parts); + + // check if the order needs to be updated, otherwise don't touch as we might change valid CS (to other valid CS). + if ($sortedParts === $parts) { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } else { + $namespace .= $firstIndent.implode($separator, $parts).($hasGroupTrailingComma ? ',' : '').$lastIndent.'}'; + } + } else { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } + + \assert('' !== $namespace); + + $indices[$startIndex] = [ + 'namespace' => $namespace, + 'startIndex' => $startIndex, + 'endIndex' => $index - 1, + 'importType' => $type, + 'group' => $group, + ]; + + $originalIndices[] = $startIndex; + + if ($index === $endIndex) { + break; + } + + $namespaceTokens = []; + $nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, [',', [\T_WHITESPACE]]); + \assert(\is_int($nextPartIndex)); + $startIndex = $nextPartIndex; + $index = $nextPartIndex; + + continue; + } + + $namespaceTokens[] = $token; + ++$index; + } + } + + // Is sort types provided, sorting by groups and each group by algorithm + if (null !== $this->configuration['imports_order']) { + // Grouping indices by import type. + $groupedByTypes = []; + + foreach ($indices as $startIndex => $item) { + $groupedByTypes[$item['importType']][$startIndex] = $item; + } + + // Sorting each group by algorithm. + foreach ($groupedByTypes as $type => $groupIndices) { + $groupedByTypes[$type] = $this->sortByAlgorithm($groupIndices); + } + + // Ordering groups + $sortedGroups = []; + + foreach ($this->configuration['imports_order'] as $type) { + if (isset($groupedByTypes[$type]) && [] !== $groupedByTypes[$type]) { + foreach ($groupedByTypes[$type] as $startIndex => $item) { + $sortedGroups[$startIndex] = $item; + } + } + } + + $indices = $sortedGroups; + } else { + // Sorting only by algorithm + $indices = $this->sortByAlgorithm($indices); + } + + $index = -1; + $usesOrder = []; + + // Loop through the index but use original index order + foreach ($indices as $v) { + ++$index; + \assert(isset($originalIndices[$index])); + $usesOrder[$originalIndices[$index]] = $v; + } + + return $usesOrder; + } + + /** + * @param array $indices + * + * @return array + */ + private function sortByAlgorithm(array $indices): array + { + if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { + uasort($indices, [$this, 'sortAlphabetically']); + } elseif (self::SORT_LENGTH === $this->configuration['sort_algorithm']) { + uasort($indices, [$this, 'sortByLength']); + } + + return $indices; + } + + /** + * @param array $usesOrder + */ + private function setNewOrder(Tokens $tokens, array $usesOrder): void + { + $mapStartToEnd = []; + + foreach ($usesOrder as $use) { + $mapStartToEnd[$use['startIndex']] = $use['endIndex']; + } + + // Now insert the new tokens, starting from the end + foreach (array_reverse($usesOrder, true) as $index => $use) { + $code = \sprintf( + 'getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals(',')) { + $numberOfInitialTokensToClear = 5; // clear `clearRange(0, $numberOfInitialTokensToClear - 1); + $declarationTokens->clearAt(\count($declarationTokens) - 1); // clear `;` + $declarationTokens->clearEmptyTokens(); + + \assert(isset($mapStartToEnd[$index])); + $tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens); + + if ($use['group']) { + // a group import must start with `use` and cannot be part of comma separated import list + self::fixCommaToUse($tokens, $tokens->getPrevMeaningfulToken($index)); + + $closeGroupIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]); + self::fixCommaToUse($tokens, $tokens->getNextMeaningfulToken($closeGroupIndex)); + } + } + } + + private static function fixCommaToUse(Tokens $tokens, int $index): void + { + if (!$tokens[$index]->equals(',')) { + return; + } + + $tokens[$index] = new Token(';'); + $tokens->insertAt($index + 1, new Token([\T_USE, 'use'])); + + if (!$tokens[$index + 2]->isWhitespace()) { + $tokens->insertAt($index + 2, new Token([\T_WHITESPACE, ' '])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php new file mode 100644 index 0000000..f834f42 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php @@ -0,0 +1,280 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * group_to_single_imports?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * group_to_single_imports: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleImportPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be one use keyword per declaration.', + [ + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoLeadingImportSlashFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, SpaceAfterSemicolonFixer. + */ + public function getPriority(): int + { + return 1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach (array_reverse($tokensAnalyzer->getImportUseIndexes()) as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + $groupClose = $tokens->getPrevMeaningfulToken($endIndex); + + if ($tokens[$groupClose]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + if (true === $this->configuration['group_to_single_imports']) { + $this->fixGroupUse($tokens, $index, $endIndex); + } + } else { + $this->fixMultipleUse($tokens, $index, $endIndex); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('group_to_single_imports', 'Whether to change group imports into single imports.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @return array{string, ?int, int, string} + */ + private function getGroupDeclaration(Tokens $tokens, int $index): array + { + $groupPrefix = ''; + $comment = ''; + $groupOpenIndex = null; + + for ($i = $index + 1;; ++$i) { + if ($tokens[$i]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $groupOpenIndex = $i; + + break; + } + + if ($tokens[$i]->isComment()) { + $comment .= $tokens[$i]->getContent(); + if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i + 1]->isWhitespace()) { + $groupPrefix .= ' '; + } + + continue; + } + + if ($tokens[$i]->isWhitespace()) { + $groupPrefix .= ' '; + + continue; + } + + $groupPrefix .= $tokens[$i]->getContent(); + } + + return [ + rtrim($groupPrefix), + $groupOpenIndex, + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupOpenIndex), + $comment, + ]; + } + + /** + * @return list + */ + private function getGroupStatements(Tokens $tokens, string $groupPrefix, int $groupOpenIndex, int $groupCloseIndex, string $comment): array + { + $statements = []; + $statement = $groupPrefix; + + for ($i = $groupOpenIndex + 1; $i <= $groupCloseIndex; ++$i) { + $token = $tokens[$i]; + + if ($token->equals(',') && $tokens[$tokens->getNextMeaningfulToken($i)]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + continue; + } + + if ($token->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) { + $statements[] = 'use'.$statement.';'; + $statement = $groupPrefix; + + continue; + } + + if ($token->isWhitespace()) { + $j = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$j]->isGivenKind(\T_AS)) { + $statement .= ' as '; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $statement = ' function'.$statement; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_CONST_IMPORT)) { + $statement = ' const'.$statement; + $i += 2; + } + + if ($token->isWhitespace(" \t") || !str_starts_with($tokens[$i - 1]->getContent(), '//')) { + continue; + } + } + + $statement .= $token->getContent(); + } + + if ('' !== $comment) { + $statements[0] .= ' '.$comment; + } + + return $statements; + } + + private function fixGroupUse(Tokens $tokens, int $index, int $endIndex): void + { + [$groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment] = $this->getGroupDeclaration($tokens, $index); + $statements = $this->getGroupStatements($tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment); + + $tokens->clearRange($index, $groupCloseIndex); + if ($tokens[$endIndex]->equals(';')) { + $tokens->clearAt($endIndex); + } + + $ending = $this->whitespacesConfig->getLineEnding(); + $importTokens = Tokens::fromCode('clearAt(0); + $importTokens->clearEmptyTokens(); + + $tokens->insertAt($index, $importTokens); + } + + private function fixMultipleUse(Tokens $tokens, int $index, int $endIndex): void + { + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextTokenIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $leadingTokens = [ + new Token([CT::T_FUNCTION_IMPORT, 'function']), + new Token([\T_WHITESPACE, ' ']), + ]; + } elseif ($tokens[$nextTokenIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $leadingTokens = [ + new Token([CT::T_CONST_IMPORT, 'const']), + new Token([\T_WHITESPACE, ' ']), + ]; + } else { + $leadingTokens = []; + } + + $ending = $this->whitespacesConfig->getLineEnding(); + + for ($i = $endIndex - 1; $i > $index; --$i) { + if (!$tokens[$i]->equals(',')) { + continue; + } + + $tokens[$i] = new Token(';'); + $i = $tokens->getNextMeaningfulToken($i); + + $tokens->insertAt($i, new Token([\T_USE, 'use'])); + $tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' '])); + + foreach ($leadingTokens as $offset => $leadingToken) { + $tokens->insertAt($i + 2 + $offset, clone $leadingToken); + } + + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + + if ($tokens[$i - 1]->isWhitespace()) { + $tokens[$i - 1] = new Token([\T_WHITESPACE, $ending.$indent]); + } elseif (!str_contains($tokens[$i - 1]->getContent(), "\n")) { + $tokens->insertAt($i, new Token([\T_WHITESPACE, $ending.$indent])); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php new file mode 100644 index 0000000..af70312 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php @@ -0,0 +1,158 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Ceeram + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleLineAfterImportsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_USE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.', + [ + new CodeSample( + <<<'PHP' + whitespacesConfig->getLineEnding(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $added = 0; + foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { + $index += $added; + $indent = ''; + + // if previous line ends with comment and current line starts with whitespace, use current indent + if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(\T_COMMENT)) { + $indent = $tokens[$index - 1]->getContent(); + } elseif ($tokens[$index - 1]->isWhitespace()) { + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]); + } + + $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); // Handle insert index for inline T_COMMENT with whitespace after semicolon + $insertIndex = $semicolonIndex; + + if ($tokens[$semicolonIndex]->isGivenKind(\T_CLOSE_TAG)) { + if ($tokens[$insertIndex - 1]->isWhitespace()) { + --$insertIndex; + } + + $tokens->insertAt($insertIndex, new Token(';')); + ++$added; + } + + if ($semicolonIndex === \count($tokens) - 1) { + $tokens->insertAt($insertIndex + 1, new Token([\T_WHITESPACE, $ending.$ending.$indent])); + ++$added; + } else { + $newline = $ending; + $tokens[$semicolonIndex]->isGivenKind(\T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex; + if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) { + ++$insertIndex; + } + + // Increment insert index for inline T_COMMENT or T_DOC_COMMENT + if ($tokens[$insertIndex]->isComment()) { + ++$insertIndex; + } + + $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex); + if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(\T_USE)) { + $newline .= $ending; + } + + if ($tokens[$insertIndex]->isWhitespace()) { + $nextToken = $tokens[$insertIndex]; + if (2 === substr_count($nextToken->getContent(), "\n")) { + continue; + } + $nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex); + if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(\T_USE)) { + if (substr_count($nextToken->getContent(), "\n") < 1) { + $tokens[$insertIndex] = new Token([\T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); + } + } else { + $tokens[$insertIndex] = new Token([\T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]); + } + } else { + $tokens->insertAt($insertIndex, new Token([\T_WHITESPACE, $newline.$indent])); + ++$added; + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/IndentationTrait.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/IndentationTrait.php new file mode 100644 index 0000000..f40ce4c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/IndentationTrait.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @phpstan-require-implements FixerInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +trait IndentationTrait +{ + private function getLineIndentation(Tokens $tokens, int $index): string + { + $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index); + + if (null === $newlineTokenIndex) { + return ''; + } + + return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex)); + } + + private function extractIndent(string $content): string + { + if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) { + return $matches[1]; + } + + return ''; + } + + private function getPreviousNewlineTokenIndex(Tokens $tokens, int $index): ?int + { + while ($index > 0) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_WHITESPACE], [\T_INLINE_HTML]]); + + if (null === $index) { + break; + } + + if ($this->isNewLineToken($tokens, $index)) { + return $index; + } + } + + return null; + } + + private function computeNewLineContent(Tokens $tokens, int $index): string + { + $content = $tokens[$index]->getContent(); + + if (0 !== $index && $tokens[$index - 1]->isGivenKind([\T_OPEN_TAG, \T_CLOSE_TAG])) { + $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content; + } + + return $content; + } + + private function isNewLineToken(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(\T_OPEN_TAG) + && isset($tokens[$index + 1]) + && !$tokens[$index + 1]->isWhitespace() + && Preg::match('/\R/', $token->getContent()) + ) { + return true; + } + + if (!$tokens[$index]->isGivenKind([\T_WHITESPACE, \T_INLINE_HTML])) { + return false; + } + + return Preg::match('/\R/', $this->computeNewLineContent($tokens, $index)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/InternalFixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/InternalFixerInterface.php new file mode 100644 index 0000000..3a52651 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/InternalFixerInterface.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface InternalFixerInterface extends FixerInterface {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordFixer.php new file mode 100644 index 0000000..33114ba --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordFixer.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ExperimentalFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassKeywordFixer extends AbstractFixer implements ExperimentalFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts FQCN strings to `*::class` keywords.', + [ + new CodeSample( + <<<'PHP' + count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $name = substr($token->getContent(), 1, -1); + $name = ltrim($name, '\\'); + $name = str_replace('\\\\', '\\', $name); + + if ($this->exists($name)) { + $substitution = Tokens::fromCode("clearRange(0, 2); + $substitution->clearAt($substitution->getSize() - 1); + $substitution->clearEmptyTokens(); + + $tokens->clearAt($index); + $tokens->insertAt($index, $substitution); + } + } + } + } + + private function exists(string $name): bool + { + if (class_exists($name) || interface_exists($name) || trait_exists($name)) { + $rc = new \ReflectionClass($name); + + return $rc->getName() === $name; + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php new file mode 100644 index 0000000..76a17fe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php @@ -0,0 +1,237 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @deprecated + * + * @author Sullivan Senechal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassKeywordRemoveFixer extends AbstractFixer implements DeprecatedFixerInterface +{ + /** + * @var array + */ + private array $imports = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts `::class` keywords to FQCN strings.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(CT::T_CLASS_CONSTANT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $previousNamespaceScopeEndIndex = 0; + foreach ($tokens->getNamespaceDeclarations() as $declaration) { + $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $declaration->getStartIndex()); + $this->replaceClassKeywordsSection($tokens, $declaration->getFullName(), $declaration->getStartIndex(), $declaration->getScopeEndIndex()); + $previousNamespaceScopeEndIndex = $declaration->getScopeEndIndex(); + } + + $this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $tokens->count() - 1); + } + + private function storeImports(Tokens $tokens, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $this->imports = []; + + foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { + if ($index < $startIndex || $index > $endIndex) { + continue; + } + + $import = ''; + while (($index = $tokens->getNextMeaningfulToken($index)) !== null) { + if ($tokens[$index]->equalsAny([';', [CT::T_GROUP_IMPORT_BRACE_OPEN]]) || $tokens[$index]->isGivenKind(\T_AS)) { + break; + } + + $import .= $tokens[$index]->getContent(); + } + + // Imports group (PHP 7 spec) + if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $groupEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $index); + $groupImports = array_map( + static fn (string $import): string => trim($import), + explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1)), + ); + foreach ($groupImports as $groupImport) { + $groupImportParts = array_map(static fn (string $import): string => trim($import), explode(' as ', $groupImport)); + if (2 === \count($groupImportParts)) { + $this->imports[$groupImportParts[1]] = $import.$groupImportParts[0]; + } else { + $this->imports[] = $import.$groupImport; + } + } + } elseif ($tokens[$index]->isGivenKind(\T_AS)) { + $aliasIndex = $tokens->getNextMeaningfulToken($index); + $alias = $tokens[$aliasIndex]->getContent(); + $this->imports[$alias] = $import; + } else { + $this->imports[] = $import; + } + } + } + + private function replaceClassKeywordsSection(Tokens $tokens, string $namespace, int $startIndex, int $endIndex): void + { + if ($endIndex - $startIndex < 3) { + return; + } + + $this->storeImports($tokens, $startIndex, $endIndex); + + $ctClassTokens = $tokens->findGivenKind(CT::T_CLASS_CONSTANT, $startIndex, $endIndex); + foreach (array_reverse(array_keys($ctClassTokens)) as $classIndex) { + $this->replaceClassKeyword($tokens, $namespace, $classIndex); + } + } + + private function replaceClassKeyword(Tokens $tokens, string $namespacePrefix, int $classIndex): void + { + $classEndIndex = $tokens->getPrevMeaningfulToken($classIndex); + $classEndIndex = $tokens->getPrevMeaningfulToken($classEndIndex); + + if (!$tokens[$classEndIndex]->isGivenKind(\T_STRING)) { + return; + } + + if ($tokens[$classEndIndex]->equalsAny([[\T_STRING, 'self'], [\T_STATIC, 'static'], [\T_STRING, 'parent']], false)) { + return; + } + + $classBeginIndex = $classEndIndex; + while (true) { + $prev = $tokens->getPrevMeaningfulToken($classBeginIndex); + if (!$tokens[$prev]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) { + break; + } + + $classBeginIndex = $prev; + } + + $classString = $tokens->generatePartialCode( + $tokens[$classBeginIndex]->isGivenKind(\T_NS_SEPARATOR) + ? $tokens->getNextMeaningfulToken($classBeginIndex) + : $classBeginIndex, + $classEndIndex, + ); + + $classImport = false; + if ($tokens[$classBeginIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $namespacePrefix = ''; + } else { + foreach ($this->imports as $alias => $import) { + if ($classString === $alias) { + $classImport = $import; + + break; + } + + $classStringArray = explode('\\', $classString); + $namespaceToTest = $classStringArray[0]; + + if (0 === ($namespaceToTest <=> substr($import, -\strlen($namespaceToTest)))) { + $classImport = $import; + + break; + } + } + } + + for ($i = $classBeginIndex; $i <= $classIndex; ++$i) { + if (!$tokens[$i]->isComment() && !($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n"))) { + $tokens->clearAt($i); + } + } + + $tokens->insertAt($classBeginIndex, new Token([ + \T_CONSTANT_ENCAPSED_STRING, + "'".$this->makeClassFQN($namespacePrefix, $classImport, $classString)."'", + ])); + } + + /** + * @param false|string $classImport + */ + private function makeClassFQN(string $namespacePrefix, $classImport, string $classString): string + { + if (false === $classImport) { + return ('' !== $namespacePrefix ? ($namespacePrefix.'\\') : '').$classString; + } + + $classStringArray = explode('\\', $classString); + $classStringLength = \count($classStringArray); + $classImportArray = explode('\\', $classImport); + $classImportLength = \count($classImportArray); + + if (1 === $classStringLength) { + return $classImport; + } + + return implode('\\', array_merge( + \array_slice($classImportArray, 0, $classImportLength - $classStringLength + 1), + $classStringArray, + )); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php new file mode 100644 index 0000000..931a110 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php @@ -0,0 +1,166 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CombineConsecutiveIssetsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Using `isset($var) &&` multiple times should be done in one call.', + [new CodeSample("isAllTokenKindsFound([\T_ISSET, \T_BOOLEAN_AND]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = $tokens->count(); + + for ($index = 1; $index < $tokenCount; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_ISSET) + || !$tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['(', '{', ';', '=', [\T_OPEN_TAG], [\T_BOOLEAN_AND], [\T_BOOLEAN_OR]])) { + continue; + } + + $issetInfo = $this->getIssetInfo($tokens, $index); + $issetCloseBraceIndex = end($issetInfo); // ')' token + $insertLocation = (int) prev($issetInfo) + 1; // one index after the previous meaningful of ')' + + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + + while ($tokens[$booleanAndTokenIndex]->isGivenKind(\T_BOOLEAN_AND)) { + $issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex); + if (!$tokens[$issetIndex]->isGivenKind(\T_ISSET)) { + $index = $issetIndex; + + break; + } + + // fetch info about the 'isset' statement that we're merging + $nextIssetInfo = $this->getIssetInfo($tokens, $issetIndex); + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken(end($nextIssetInfo)); + $nextMeaningfulToken = $tokens[$nextMeaningfulTokenIndex]; + + if (!$nextMeaningfulToken->equalsAny([')', '}', ';', [\T_CLOSE_TAG], [\T_BOOLEAN_AND], [\T_BOOLEAN_OR]])) { + $index = $nextMeaningfulTokenIndex; + + break; + } + + // clone what we want to move, do not clone '(' and ')' of the 'isset' statement we're merging + $clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1)); + + // clean up now the tokens of the 'isset' statement we're merging + $this->clearTokens($tokens, array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex])); + + // insert the tokens to create the new statement + array_unshift($clones, new Token(','), new Token([\T_WHITESPACE, ' '])); + $tokens->insertAt($insertLocation, $clones); + + // correct some counts and offset based on # of tokens inserted + $numberOfTokensInserted = \count($clones); + $tokenCount += $numberOfTokensInserted; + $issetCloseBraceIndex += $numberOfTokensInserted; + $insertLocation += $numberOfTokensInserted; + + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + } + } + } + + /** + * @param list $indices + */ + private function clearTokens(Tokens $tokens, array $indices): void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + /** + * @param int $index of T_ISSET + * + * @return non-empty-list indices of meaningful tokens belonging to the isset statement + */ + private function getIssetInfo(Tokens $tokens, int $index): array + { + $openIndex = $tokens->getNextMeaningfulToken($index); + + $braceOpenCount = 1; + $meaningfulTokenIndices = [$openIndex]; + + for ($i = $openIndex + 1;; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $meaningfulTokenIndices[] = $i; + + if ($tokens[$i]->equals(')')) { + --$braceOpenCount; + if (0 === $braceOpenCount) { + break; + } + } elseif ($tokens[$i]->equals('(')) { + ++$braceOpenCount; + } + } + + return $meaningfulTokenIndices; + } + + /** + * @param list $indices + * + * @return list + */ + private function getTokenClones(Tokens $tokens, array $indices): array + { + $clones = []; + + foreach ($indices as $i) { + $clones[] = clone $tokens[$i]; + } + + return $clones; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php new file mode 100644 index 0000000..8faa41d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php @@ -0,0 +1,189 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CombineConsecutiveUnsetsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Calling `unset` on multiple items should be done in one call.', + [new CodeSample("isTokenKindFound(\T_UNSET); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_UNSET)) { + continue; + } + + $previousUnsetCall = $this->getPreviousUnsetCall($tokens, $index); + if (\is_int($previousUnsetCall)) { + $index = $previousUnsetCall; + + continue; + } + + [$previousUnset, , $previousUnsetBraceEnd] = $previousUnsetCall; + + // Merge the tokens inside the 'unset' call into the previous one 'unset' call. + $tokensAddCount = $this->moveTokens( + $tokens, + $nextUnsetContentStart = $tokens->getNextTokenOfKind($index, ['(']), + $nextUnsetContentEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextUnsetContentStart), + $previousUnsetBraceEnd - 1, + ); + + if (!$tokens[$previousUnsetBraceEnd]->isWhitespace()) { + $tokens->insertAt($previousUnsetBraceEnd, new Token([\T_WHITESPACE, ' '])); + ++$tokensAddCount; + } + + $tokenBeforePreviousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetBraceEnd); + + if (!$tokens[$tokenBeforePreviousUnsetBraceEnd]->equals(',')) { + $tokens->insertAt($previousUnsetBraceEnd, new Token(',')); + ++$tokensAddCount; + } elseif ($tokens[$tokenBeforePreviousUnsetBraceEnd + 1]->isWhitespace()) { + // keeping trailing comma from previous `unset`, but tokens moved - may cause 2 whitespaces tokens one after another - needed to clean this up + $tokens->clearTokenAndMergeSurroundingWhitespace($tokenBeforePreviousUnsetBraceEnd + 1); + } + + // Remove 'unset', '(', ')' and (possibly) ';' from the merged 'unset' call. + $this->clearOffsetTokens($tokens, $tokensAddCount, [$index, $nextUnsetContentStart, $nextUnsetContentEnd]); + + $nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd); + if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon); + } + + $index = $previousUnset + 1; + } + } + + /** + * @param list $indices + */ + private function clearOffsetTokens(Tokens $tokens, int $offset, array $indices): void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset); + } + } + + /** + * Find a previous call to unset directly before the index. + * + * Returns an array with + * * unset index + * * opening brace index + * * closing brace index + * * end semicolon index + * + * Or the index to where the method looked for a call. + * + * @return array{int, int, int, int}|int + */ + private function getPreviousUnsetCall(Tokens $tokens, int $index) + { + $previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index); + if (null === $previousUnsetSemicolon) { + return $index; + } + + if (!$tokens[$previousUnsetSemicolon]->equals(';')) { + return $previousUnsetSemicolon; + } + + $previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon); + if (null === $previousUnsetBraceEnd) { + return $index; + } + + if (!$tokens[$previousUnsetBraceEnd]->equals(')')) { + return $previousUnsetBraceEnd; + } + + $previousUnsetBraceStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $previousUnsetBraceEnd); + $previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart); + if (null === $previousUnset) { + return $index; + } + + if (!$tokens[$previousUnset]->isGivenKind(\T_UNSET)) { + return $previousUnset; + } + + return [ + $previousUnset, + $previousUnsetBraceStart, + $previousUnsetBraceEnd, + $previousUnsetSemicolon, + ]; + } + + /** + * @param int $start Index previous of the first token to move + * @param int $end Index of the last token to move + * @param int $to Upper boundary index + * + * @return int Number of tokens inserted + */ + private function moveTokens(Tokens $tokens, int $start, int $end, int $to): int + { + $added = 0; + for ($i = $start + 1; $i < $end; $i += 2) { + if ($tokens[$i]->isWhitespace() && $tokens[$to + 1]->isWhitespace()) { + $tokens[$to + 1] = new Token([\T_WHITESPACE, $tokens[$to + 1]->getContent().$tokens[$i]->getContent()]); + } else { + $tokens->insertAt(++$to, clone $tokens[$i]); + ++$end; + ++$added; + } + + $tokens->clearAt($i + 1); + } + + return $added; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php new file mode 100644 index 0000000..47bd166 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php @@ -0,0 +1,139 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * space?: 'none'|'single', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * space: 'none'|'single', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DeclareEqualNormalizeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Equal sign in declare statement should be surrounded by spaces or not following configuration.', + [ + new CodeSample(" 'single']), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after DeclareStrictTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DECLARE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count - 6; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_DECLARE)) { + continue; + } + + $openParenthesisIndex = $tokens->getNextMeaningfulToken($index); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + + for ($i = $closeParenthesisIndex; $i > $openParenthesisIndex; --$i) { + if ($tokens[$i]->equals('=')) { + if ('none' === $this->configuration['space']) { + $this->removeWhitespaceAroundToken($tokens, $i); + } else { + $this->ensureWhitespaceAroundToken($tokens, $i); + } + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply around the equal sign.')) + ->setAllowedValues(['single', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * @param int $index of `=` token + */ + private function ensureWhitespaceAroundToken(Tokens $tokens, int $index): void + { + if ($tokens[$index + 1]->isWhitespace()) { + if (' ' !== $tokens[$index + 1]->getContent()) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + if ($tokens[$index - 1]->isWhitespace()) { + if (' ' !== $tokens[$index - 1]->getContent() && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } + } + + /** + * @param int $index of `=` token + */ + private function removeWhitespaceAroundToken(Tokens $tokens, int $index): void + { + if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + $tokens->removeTrailingWhitespace($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php new file mode 100644 index 0000000..655be34 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DeclareParenthesesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must not be spaces around `declare` statement parentheses.', + [new CodeSample("isTokenKindFound(\T_DECLARE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_DECLARE)) { + continue; + } + + $tokens->removeTrailingWhitespace($index); + + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + $tokens->removeTrailingWhitespace($startParenthesisIndex); + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startParenthesisIndex); + $tokens->removeLeadingWhitespace($endParenthesisIndex); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php new file mode 100644 index 0000000..d12a2a6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DirConstantFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `dirname(__FILE__)` expression with equivalent `__DIR__` constant.', + [new CodeSample("isAllTokenKindsFound([\T_STRING, \T_FILE]); + } + + /** + * {@inheritdoc} + * + * Must run before CombineNestedDirnameFixer. + */ + public function getPriority(): int + { + return 40; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $currIndex = 0; + + do { + $boundaries = $this->find('dirname', $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + return; + } + + [$functionNameIndex, $openParenthesis, $closeParenthesis] = $boundaries; + + // analysing cursor shift, so nested expressions kept processed + $currIndex = $openParenthesis; + + // ensure __FILE__ is in between (...) + + $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($closeParenthesis); + $trailingCommaIndex = null; + + if ($tokens[$fileCandidateRightIndex]->equals(',')) { + $trailingCommaIndex = $fileCandidateRightIndex; + $fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($fileCandidateRightIndex); + } + + $fileCandidateRight = $tokens[$fileCandidateRightIndex]; + + if (!$fileCandidateRight->isGivenKind(\T_FILE)) { + continue; + } + + $fileCandidateLeftIndex = $tokens->getNextMeaningfulToken($openParenthesis); + $fileCandidateLeft = $tokens[$fileCandidateLeftIndex]; + + if (!$fileCandidateLeft->isGivenKind(\T_FILE)) { + continue; + } + + // get rid of root namespace when it used + $namespaceCandidateIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + $namespaceCandidate = $tokens[$namespaceCandidateIndex]; + + if ($namespaceCandidate->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->removeTrailingWhitespace($namespaceCandidateIndex); + $tokens->clearAt($namespaceCandidateIndex); + } + + if (null !== $trailingCommaIndex) { + if (!$tokens[$tokens->getNextNonWhitespace($trailingCommaIndex)]->isComment()) { + $tokens->removeTrailingWhitespace($trailingCommaIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($trailingCommaIndex); + } + + // closing parenthesis removed with leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($closeParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($closeParenthesis); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesis); + + // opening parenthesis removed with trailing and leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($openParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($openParenthesis); + } + + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesis); + + // replace constant and remove function name + $tokens[$fileCandidateLeftIndex] = new Token([\T_DIR, '__DIR__']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + } while (null !== $currIndex); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php new file mode 100644 index 0000000..a30eddd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php @@ -0,0 +1,188 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * mute_deprecation_error?: bool, + * noise_remaining_usages?: bool, + * noise_remaining_usages_exclude?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * mute_deprecation_error: bool, + * noise_remaining_usages: bool, + * noise_remaining_usages_exclude: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Jules Pietri + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ErrorSuppressionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const OPTION_MUTE_DEPRECATION_ERROR = 'mute_deprecation_error'; + + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES = 'noise_remaining_usages'; + + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES_EXCLUDE = 'noise_remaining_usages_exclude'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Error control operator should be added to deprecation notices and/or removed from other cases.', + [ + new CodeSample(" true], + ), + new CodeSample( + " true, + self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE => ['unlink'], + ], + ), + ], + null, + 'Risky because adding/removing `@` might cause changes to code behaviour or if `trigger_error` function is overridden.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_MUTE_DEPRECATION_ERROR, 'Whether to add `@` in deprecation notices.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES, 'Whether to remove `@` in remaining usages.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE, 'List of global functions to exclude from removing `@`.')) + ->setAllowedTypes(['string[]']) + ->setDefault([]) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $excludedFunctions = array_map(static fn (string $function): string => strtolower($function), $this->configuration[self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE]); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && $token->equals('@')) { + $tokens->clearAt($index); + + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $functionIndex = $index; + $startIndex = $index; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $startIndex = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); + } + + $index = $prevIndex; + + if ($this->isDeprecationErrorCall($tokens, $functionIndex)) { + if (false === $this->configuration[self::OPTION_MUTE_DEPRECATION_ERROR]) { + continue; + } + + if ($tokens[$prevIndex]->equals('@')) { + continue; + } + + $tokens->insertAt($startIndex, new Token('@')); + + continue; + } + + if (!$tokens[$prevIndex]->equals('@')) { + continue; + } + + if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && !\in_array($tokens[$functionIndex]->getContent(), $excludedFunctions, true)) { + $tokens->clearAt($index); + } + } + } + + private function isDeprecationErrorCall(Tokens $tokens, int $index): bool + { + if ('trigger_error' !== strtolower($tokens[$index]->getContent())) { + return false; + } + + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $tokens->getNextTokenOfKind($index, [[\T_STRING], '('])); + $prevIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); + + if ($tokens[$prevIndex]->equals(',')) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + return $tokens[$prevIndex]->equals([\T_STRING, 'E_USER_DEPRECATED']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php new file mode 100644 index 0000000..13c8896 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ExplicitIndirectVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Add curly braces to indirect variables to make them clear to understand.', + [ + new CodeSample( + <<<'EOT' + $bar['baz']; + echo $foo->$callback($baz); + + EOT, + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_VARIABLE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 1; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind(\T_VARIABLE)) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if (!$prevToken->equals('$') && !$prevToken->isObjectOperator()) { + continue; + } + + $openingBrace = CT::T_DYNAMIC_VAR_BRACE_OPEN; + $closingBrace = CT::T_DYNAMIC_VAR_BRACE_CLOSE; + if ($prevToken->isObjectOperator()) { + $openingBrace = CT::T_DYNAMIC_PROP_BRACE_OPEN; + $closingBrace = CT::T_DYNAMIC_PROP_BRACE_CLOSE; + } + + $tokens->overrideRange($index, $index, [ + new Token([$openingBrace, '{']), + new Token([\T_VARIABLE, $token->getContent()]), + new Token([$closingBrace, '}']), + ]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php new file mode 100644 index 0000000..650c111 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php @@ -0,0 +1,313 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * functions?: list<'get_called_class'|'get_class'|'get_class_this'|'php_sapi_name'|'phpversion'|'pi'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * functions: list<'get_called_class'|'get_class'|'get_class_this'|'php_sapi_name'|'phpversion'|'pi'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FunctionToConstantFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var null|array> + */ + private static ?array $availableFunctions = null; + + /** + * @var array> + */ + private array $functionsFixMap; + + public function __construct() + { + if (null === self::$availableFunctions) { + self::$availableFunctions = [ + 'get_called_class' => [ + new Token([\T_STATIC, 'static']), + new Token([\T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ], + 'get_class' => [ + new Token([\T_STRING, 'self']), + new Token([\T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ], + 'get_class_this' => [ + new Token([\T_STATIC, 'static']), + new Token([\T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ], + 'php_sapi_name' => [new Token([\T_STRING, 'PHP_SAPI'])], + 'phpversion' => [new Token([\T_STRING, 'PHP_VERSION'])], + 'pi' => [new Token([\T_STRING, 'M_PI'])], + ]; + } + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace core functions calls returning constants with the constants.', + [ + new CodeSample( + " ['get_called_class', 'get_class_this', 'phpversion']], + ), + ], + null, + 'Risky when any of the configured functions to replace are overridden.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NativeConstantInvocationFixer, NativeFunctionCasingFixer, NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SelfStaticAccessorFixer. + * Must run after NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->functionsFixMap = []; + + foreach ($this->configuration['functions'] as $key) { + \assert(isset(self::$availableFunctions[$key])); + $this->functionsFixMap[$key] = self::$availableFunctions[$key]; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionAnalyzer = new FunctionsAnalyzer(); + + for ($index = $tokens->count() - 4; $index > 0; --$index) { + $candidate = $this->getReplaceCandidate($tokens, $functionAnalyzer, $index); + if (null === $candidate) { + continue; + } + + $this->fixFunctionCallToConstant( + $tokens, + $index, + $candidate[0], // brace open + $candidate[1], // brace close + $candidate[2], // replacement + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $functionNames = array_keys(self::$availableFunctions); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('functions', 'List of function names to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($functionNames)]) + ->setDefault([ + 'get_called_class', + 'get_class', + 'get_class_this', + 'php_sapi_name', + 'phpversion', + 'pi', + ]) + ->getOption(), + ]); + } + + /** + * @param non-empty-list $replacements + */ + private function fixFunctionCallToConstant(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex, array $replacements): void + { + for ($i = $braceCloseIndex; $i >= $braceOpenIndex; --$i) { + if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + + if ( + $replacements[0]->isGivenKind([\T_CLASS_C, \T_STATIC]) + || ($replacements[0]->isGivenKind(\T_STRING) && 'self' === $replacements[0]->getContent()) + ) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if ($prevToken->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearAt($prevIndex); + } + } + + $tokens->clearAt($index); + $tokens->insertAt($index, $replacements); + } + + /** + * @return ?array{int, int, non-empty-list} + */ + private function getReplaceCandidate( + Tokens $tokens, + FunctionsAnalyzer $functionAnalyzer, + int $index + ): ?array { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + return null; + } + + $lowerContent = strtolower($tokens[$index]->getContent()); + + if ('get_class' === $lowerContent) { + return $this->fixGetClassCall($tokens, $functionAnalyzer, $index); + } + + if (!isset($this->functionsFixMap[$lowerContent])) { + return null; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return null; + } + + // test if function call without parameters + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + \assert(\is_int($braceOpenIndex)); + + $braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex); + if (!$tokens[$braceCloseIndex]->equals(')')) { + return null; + } + + return $this->getReplacementTokenClones($lowerContent, $braceOpenIndex, $braceCloseIndex); + } + + /** + * @return ?array{int, int, non-empty-list} + */ + private function fixGetClassCall( + Tokens $tokens, + FunctionsAnalyzer $functionAnalyzer, + int $index + ): ?array { + if (!isset($this->functionsFixMap['get_class']) && !isset($this->functionsFixMap['get_class_this'])) { + return null; + } + + if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { + return null; + } + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $braceOpenIndex); + + if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { // no arguments passed + if (isset($this->functionsFixMap['get_class'])) { + return $this->getReplacementTokenClones('get_class', $braceOpenIndex, $braceCloseIndex); + } + } elseif (isset($this->functionsFixMap['get_class_this'])) { + $isThis = false; + + for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { + if ($tokens[$i]->equalsAny([[\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], ')'])) { + continue; + } + + if ($tokens[$i]->isGivenKind(\T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { + $isThis = true; + + continue; + } + + if (false === $isThis && $tokens[$i]->equals('(')) { + continue; + } + + $isThis = false; + + break; + } + + if ($isThis) { + return $this->getReplacementTokenClones('get_class_this', $braceOpenIndex, $braceCloseIndex); + } + } + + return null; + } + + /** + * @return array{int, int, non-empty-list} + */ + private function getReplacementTokenClones(string $lowerContent, int $braceOpenIndex, int $braceCloseIndex): array + { + \assert(isset($this->functionsFixMap[$lowerContent])); + $clones = array_map( + static fn (Token $token): Token => clone $token, + $this->functionsFixMap[$lowerContent], + ); + + return [ + $braceOpenIndex, + $braceCloseIndex, + $clones, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php new file mode 100644 index 0000000..4d2cb34 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author John Paul E. Balandan, CPA + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GetClassToClassKeywordFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace `get_class` calls on object variables with class keyword syntax.', + [ + new VersionSpecificCodeSample( + "= 8_00_00 && $tokens->isAllTokenKindsFound([\T_STRING, \T_VARIABLE]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $indicesToClear = []; + $tokenSlices = []; + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals([\T_STRING, 'get_class'], false)) { + continue; + } + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $braceOpenIndex); + + if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { + continue; // get_class with no arguments + } + + $meaningfulTokensCount = 0; + $variableTokensIndices = []; + + for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { + if (!$tokens[$i]->equalsAny([[\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], '(', ')'])) { + ++$meaningfulTokensCount; + } + + if (!$tokens[$i]->isGivenKind(\T_VARIABLE)) { + continue; + } + + if ('$this' === strtolower($tokens[$i]->getContent())) { + continue 2; // get_class($this) + } + + $variableTokensIndices[] = $i; + } + + if ($meaningfulTokensCount > 1 || 1 !== \count($variableTokensIndices)) { + continue; // argument contains more logic, or more arguments, or no variable argument + } + + $indicesToClear[$index] = [$braceOpenIndex, current($variableTokensIndices), $braceCloseIndex]; + } + + foreach ($indicesToClear as $index => $items) { + $tokenSlices[$index] = $this->getReplacementTokenSlices($tokens, $items[1]); + $this->clearGetClassCall($tokens, $index, $items[0], $items[2]); + } + + $tokens->insertSlices($tokenSlices); + } + + /** + * @return non-empty-list + */ + private function getReplacementTokenSlices(Tokens $tokens, int $variableIndex): array + { + return [ + new Token([\T_VARIABLE, $tokens[$variableIndex]->getContent()]), + new Token([\T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ]; + } + + private function clearGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex): void + { + for ($i = $braceOpenIndex; $i <= $braceCloseIndex; ++$i) { + if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearAt($prevIndex); + } + + $tokens->clearAt($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php new file mode 100644 index 0000000..938614b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php @@ -0,0 +1,171 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Reznichenko + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class IsNullFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replaces `is_null($var)` expression with `null === $var`.', + [ + new CodeSample("isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $currIndex = 0; + + while (true) { + // recalculate "end" because we might have added tokens in previous iteration + $matches = $tokens->findSequence([[\T_STRING, 'is_null'], '('], $currIndex, $tokens->count() - 1, false); + + // stop looping if didn't find any new matches + if (null === $matches) { + break; + } + + // 0 and 1 accordingly are "is_null", "(" tokens + $matches = array_keys($matches); + \assert(isset($matches[1])); + + // move the cursor just after the sequence + [$isNullIndex, $currIndex] = $matches; + + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $matches[0])) { + continue; + } + + $next = $tokens->getNextMeaningfulToken($currIndex); + + if ($tokens[$next]->equals(')')) { + continue; + } + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($matches[0]); + + // handle function references with namespaces + if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + + $prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); + } + + // check if inversion being used, text comparison is due to not existing constant + $isInvertedNullCheck = false; + + if ($tokens[$prevTokenIndex]->equals('!')) { + $isInvertedNullCheck = true; + + // get rid of inverting for proper transformations + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + + // before getting rind of `()` around a parameter, ensure it's not assignment/ternary invariant + $referenceEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $matches[1]); + $isContainingDangerousConstructs = false; + + for ($paramTokenIndex = $matches[1]; $paramTokenIndex <= $referenceEnd; ++$paramTokenIndex) { + if (\in_array($tokens[$paramTokenIndex]->getContent(), ['?', '?:', '=', '??'], true)) { + $isContainingDangerousConstructs = true; + + break; + } + } + + // edge cases: is_null() followed/preceded by ==, ===, !=, !==, <>, (int-or-other-casting) + $parentLeftToken = $tokens[$tokens->getPrevMeaningfulToken($isNullIndex)]; + $parentRightToken = $tokens[$tokens->getNextMeaningfulToken($referenceEnd)]; + $parentOperations = [\T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL]; + $wrapIntoParentheses = $parentLeftToken->isCast() || $parentLeftToken->isGivenKind($parentOperations) || $parentRightToken->isGivenKind($parentOperations); + + // possible trailing comma removed + $prevIndex = $tokens->getPrevMeaningfulToken($referenceEnd); + + if ($tokens[$prevIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + + if (!$isContainingDangerousConstructs) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($referenceEnd); + $tokens->clearAt($referenceEnd); + + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($matches[1]); + $tokens->removeTrailingWhitespace($matches[1]); + $tokens->clearAt($matches[1]); + } + + // sequence which we'll use as a replacement + $replacement = [ + new Token([\T_STRING, 'null']), + new Token([\T_WHITESPACE, ' ']), + new Token($isInvertedNullCheck ? [\T_IS_NOT_IDENTICAL, '!=='] : [\T_IS_IDENTICAL, '===']), + new Token([\T_WHITESPACE, ' ']), + ]; + + if ($wrapIntoParentheses) { + array_unshift($replacement, new Token('(')); + $tokens->insertAt($referenceEnd + 1, new Token(')')); + } + + $tokens->overrideRange($isNullIndex, $isNullIndex, $replacement); + + // nested is_null calls support + $currIndex = $isNullIndex; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php new file mode 100644 index 0000000..9f0f13c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php @@ -0,0 +1,229 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _UnsetInfo array{ + * startIndex: int, + * endIndex: int, + * isToTransform: bool, + * isFirst: bool, + * } + * + * @author Gert de Pagter + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUnsetOnPropertyFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Properties should be set to `null` instead of using `unset`.', + [new CodeSample("a);\n")], + null, + 'Risky when relying on attributes to be removed using `unset` rather than be set to `null`.' + .' Changing variables to `null` instead of unsetting means these still show up when looping over class variables' + .' and reference properties remain unbroken.' + .' Since PHP 7.4, this rule might introduce `null` assignments to properties whose type declaration does not allow it.', + ); + } + + public function isRisky(): bool + { + return true; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_UNSET) + && $tokens->isAnyTokenKindsFound([\T_OBJECT_OPERATOR, \T_PAAMAYIM_NEKUDOTAYIM]); + } + + /** + * {@inheritdoc} + * + * Must run before CombineConsecutiveUnsetsFixer. + */ + public function getPriority(): int + { + return 25; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_UNSET)) { + continue; + } + + $unsetsInfo = $this->getUnsetsInfo($tokens, $index); + + if (!$this->isAnyUnsetToTransform($unsetsInfo)) { + continue; + } + + $isLastUnset = true; // "last" as we reverse the array below + + foreach (array_reverse($unsetsInfo) as $unsetInfo) { + $this->updateTokens($tokens, $unsetInfo, $isLastUnset); + $isLastUnset = false; + } + } + } + + /** + * @return list<_UnsetInfo> + */ + private function getUnsetsInfo(Tokens $tokens, int $index): array + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $unsetStart = $tokens->getNextTokenOfKind($index, ['(']); + $unsetEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $unsetStart); + $isFirst = true; + $unsets = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $unsetStart, $unsetEnd) as $startIndex => $endIndex) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex - 1); + $endIndex = $tokens->getPrevMeaningfulToken($endIndex + 1); + $unsets[] = [ + 'startIndex' => $startIndex, + 'endIndex' => $endIndex, + 'isToTransform' => $this->isProperty($tokens, $startIndex, $endIndex), + 'isFirst' => $isFirst, + ]; + $isFirst = false; + } + + return $unsets; + } + + private function isProperty(Tokens $tokens, int $index, int $endIndex): bool + { + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex || !$tokens[$nextIndex]->isGivenKind(\T_OBJECT_OPERATOR)) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { + return false; + } + + return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(\T_STRING); + } + + if ($tokens[$index]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) { + $nextIndex = $tokens->getTokenNotOfKindsSibling($index, 1, [\T_DOUBLE_COLON, \T_NS_SEPARATOR, \T_STRING]); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $nextNextIndex < $endIndex) { + return false; + } + + return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(\T_VARIABLE); + } + + return false; + } + + /** + * @param list<_UnsetInfo> $unsetsInfo + */ + private function isAnyUnsetToTransform(array $unsetsInfo): bool + { + foreach ($unsetsInfo as $unsetInfo) { + if ($unsetInfo['isToTransform']) { + return true; + } + } + + return false; + } + + /** + * @param _UnsetInfo $unsetInfo + */ + private function updateTokens(Tokens $tokens, array $unsetInfo, bool $isLastUnset): void + { + // if entry is first and to be transformed we remove leading "unset(" + if ($unsetInfo['isFirst'] && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getPrevTokenOfKind($unsetInfo['startIndex'], ['(']); + $unsetIndex = $tokens->getPrevTokenOfKind($braceIndex, [[\T_UNSET]]); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($unsetIndex); + } + + // if entry is last and to be transformed we remove trailing ")" + if ($isLastUnset && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [')']); + $previousIndex = $tokens->getPrevMeaningfulToken($braceIndex); + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousIndex); // trailing ',' in function call (PHP 7.3) + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + } + + // if entry is not last we replace comma with semicolon (last entry already has semicolon - from original unset) + if (!$isLastUnset) { + $commaIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [',']); + $tokens[$commaIndex] = new Token(';'); + } + + // if entry is to be unset and is not last we add trailing ")" + if (!$unsetInfo['isToTransform'] && !$isLastUnset) { + $tokens->insertAt($unsetInfo['endIndex'] + 1, new Token(')')); + } + + // if entry is to be unset and is not first we add leading "unset(" + if (!$unsetInfo['isToTransform'] && !$unsetInfo['isFirst']) { + $tokens->insertAt( + $unsetInfo['startIndex'], + [ + new Token([\T_UNSET, 'unset']), + new Token('('), + ], + ); + } + + // and finally + // if entry is to be transformed we add trailing " = null" + if ($unsetInfo['isToTransform']) { + $tokens->insertAt( + $unsetInfo['endIndex'] + 1, + [ + new Token([\T_WHITESPACE, ' ']), + new Token('='), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_STRING, 'null']), + ], + ); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php new file mode 100644 index 0000000..2cfedf0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php @@ -0,0 +1,356 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * syntax?: 'question_mark'|'union', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * syntax: 'question_mark'|'union', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author John Paul E. Balandan, CPA + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullableTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const OPTION_SYNTAX_UNION = 'union'; + private const OPTION_SYNTAX_QUESTION_MARK = 'question_mark'; + private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_ABSTRACT, \T_FINAL, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + private int $candidateTokenKind; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Nullable single type declaration should be standardised using configured syntax.', + [ + new VersionSpecificCodeSample( + <<<'PHP' + self::OPTION_SYNTAX_UNION], + ), + new VersionSpecificCodeSample( + <<<'PHP' + self::OPTION_SYNTAX_QUESTION_MARK], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_00_00 && $tokens->isTokenKindFound($this->candidateTokenKind); + } + + /** + * {@inheritdoc} + * + * Must run before OrderedTypesFixer, TypesSpacesFixer. + * Must run after NullableTypeDeclarationForDefaultNullValueFixer. + */ + public function getPriority(): int + { + return 2; + } + + protected function configurePostNormalisation(): void + { + $this->candidateTokenKind = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax'] + ? CT::T_TYPE_ALTERNATION // `|` -> `?` + : CT::T_NULLABLE_TYPE; // `?` -> `|` + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use question mark (`?`) or explicit `null` union for nullable type.')) + ->setAllowedValues([self::OPTION_SYNTAX_UNION, self::OPTION_SYNTAX_QUESTION_MARK]) + ->setDefault(self::OPTION_SYNTAX_QUESTION_MARK) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (array_reverse($this->getElements($tokens), true) as $index => $type) { + if ('property' === $type) { + $this->normalizePropertyType($tokens, $index); + + continue; + } + + $this->normalizeMethodReturnType($functionsAnalyzer, $tokens, $index); + $this->normalizeMethodArgumentType($functionsAnalyzer, $tokens, $index); + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => 'method' === $element['type'] ? 'function' : $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true), + ), + ); + + foreach ($tokens as $index => $token) { + if ( + $token->isGivenKind(\T_FN) + || ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'function'; + } + } + + return $elements; + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + + private function isTypeNormalizable(TypeAnalysis $typeAnalysis): bool + { + $type = $typeAnalysis->getName(); + + if ('null' === strtolower($type) || !$typeAnalysis->isNullable()) { + return false; + } + + if (str_contains($type, '&')) { + return false; // skip DNF types + } + + if (!str_contains($type, '|')) { + return true; + } + + return 1 === substr_count($type, '|') && Preg::match('/(?:\|null$|^null\|)/i', $type); + } + + private function normalizePropertyType(Tokens $tokens, int $index): void + { + $propertyEndIndex = $index; + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyEndIndex); + + if (null === $propertyType || !$this->isTypeNormalizable($propertyType)) { + return; + } + + $this->normalizeNullableType($tokens, $propertyType); + } + + private function normalizeMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index), true) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType || !$this->isTypeNormalizable($argumentType)) { + continue; + } + + $this->normalizeNullableType($tokens, $argumentType); + } + } + + private function normalizeMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + + if (null === $returnType || !$this->isTypeNormalizable($returnType)) { + return; + } + + $this->normalizeNullableType($tokens, $returnType); + } + + private function normalizeNullableType(Tokens $tokens, TypeAnalysis $typeAnalysis): void + { + $type = $typeAnalysis->getName(); + + if (!str_contains($type, '|') && !str_contains($type, '&')) { + $type = ($typeAnalysis->isNullable() ? '?' : '').$type; + } + + $isQuestionMarkSyntax = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax']; + + if ($isQuestionMarkSyntax) { + $normalizedType = $this->convertToNullableType($type); + $normalizedTypeAsString = implode('', $normalizedType); + } else { + $normalizedType = $this->convertToExplicitUnionType($type); + $normalizedTypeAsString = implode('|', $normalizedType); + } + + if ($normalizedTypeAsString === $type) { + return; // nothing to fix + } + + $tokens->overrideRange( + $typeAnalysis->getStartIndex(), + $typeAnalysis->getEndIndex(), + $this->createTypeDeclarationTokens($normalizedType, $isQuestionMarkSyntax), + ); + + $prevStartIndex = $typeAnalysis->getStartIndex() - 1; + if (!$tokens[$prevStartIndex]->isWhitespace() && !$tokens[$prevStartIndex]->equals('(')) { + $tokens->ensureWhitespaceAtIndex($prevStartIndex, 1, ' '); + } + } + + /** + * @return array{0: string, 1?: string} + */ + private function convertToNullableType(string $type): array + { + if (str_starts_with($type, '?')) { + return [$type]; // no need to convert; already fixed + } + + return ['?', Preg::replace('/(?:\|null$|^null\|)/i', '', $type)]; + } + + /** + * @return array{0: string, 1?: string} + */ + private function convertToExplicitUnionType(string $type): array + { + if (str_contains($type, '|')) { + return [$type]; // no need to convert; already fixed + } + + return ['null', substr($type, 1)]; + } + + /** + * @param list $types + * + * @return list + */ + private function createTypeDeclarationTokens(array $types, bool $isQuestionMarkSyntax): array + { + $count = \count($types); + $newTokens = []; + + foreach ($types as $index => $type) { + $specialType = [ + '?' => CT::T_NULLABLE_TYPE, + 'array' => CT::T_ARRAY_TYPEHINT, + 'callable' => \T_CALLABLE, + 'static' => \T_STATIC, + ][strtolower($type)] ?? null; + + if (null !== $specialType) { + $newTokens[] = new Token([$specialType, $type]); + } else { + foreach (explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + + if ($nsIndex > 0) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + + $newTokens[] = new Token([\T_STRING, $value]); + } + } + + if ($index <= $count - 2 && !$isQuestionMarkSyntax) { + $newTokens[] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } + } + + return $newTokens; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php new file mode 100644 index 0000000..d4aedbc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php @@ -0,0 +1,217 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; + +/** + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * constructs?: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'protected'|'public'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * constructs: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'protected'|'public'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleSpaceAfterConstructFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private const TOKEN_MAP = [ + 'abstract' => \T_ABSTRACT, + 'as' => \T_AS, + 'attribute' => CT::T_ATTRIBUTE_CLOSE, + 'break' => \T_BREAK, + 'case' => \T_CASE, + 'catch' => \T_CATCH, + 'class' => \T_CLASS, + 'clone' => \T_CLONE, + 'comment' => \T_COMMENT, + 'const' => \T_CONST, + 'const_import' => CT::T_CONST_IMPORT, + 'continue' => \T_CONTINUE, + 'do' => \T_DO, + 'echo' => \T_ECHO, + 'else' => \T_ELSE, + 'elseif' => \T_ELSEIF, + 'enum' => null, + 'extends' => \T_EXTENDS, + 'final' => \T_FINAL, + 'finally' => \T_FINALLY, + 'for' => \T_FOR, + 'foreach' => \T_FOREACH, + 'function' => \T_FUNCTION, + 'function_import' => CT::T_FUNCTION_IMPORT, + 'global' => \T_GLOBAL, + 'goto' => \T_GOTO, + 'if' => \T_IF, + 'implements' => \T_IMPLEMENTS, + 'include' => \T_INCLUDE, + 'include_once' => \T_INCLUDE_ONCE, + 'instanceof' => \T_INSTANCEOF, + 'insteadof' => \T_INSTEADOF, + 'interface' => \T_INTERFACE, + 'match' => null, + 'named_argument' => CT::T_NAMED_ARGUMENT_COLON, + 'namespace' => \T_NAMESPACE, + 'new' => \T_NEW, + 'open_tag_with_echo' => \T_OPEN_TAG_WITH_ECHO, + 'php_doc' => \T_DOC_COMMENT, + 'php_open' => \T_OPEN_TAG, + 'print' => \T_PRINT, + 'private' => \T_PRIVATE, + 'protected' => \T_PROTECTED, + 'public' => \T_PUBLIC, + 'readonly' => null, + 'require' => \T_REQUIRE, + 'require_once' => \T_REQUIRE_ONCE, + 'return' => \T_RETURN, + 'static' => \T_STATIC, + 'switch' => \T_SWITCH, + 'throw' => \T_THROW, + 'trait' => \T_TRAIT, + 'try' => \T_TRY, + 'type_colon' => CT::T_TYPE_COLON, + 'use' => \T_USE, + 'use_lambda' => CT::T_USE_LAMBDA, + 'use_trait' => CT::T_USE_TRAIT, + 'var' => \T_VAR, + 'while' => \T_WHILE, + 'yield' => \T_YIELD, + 'yield_from' => \T_YIELD_FROM, + ]; + + private SingleSpaceAroundConstructFixer $singleSpaceAroundConstructFixer; + + public function __construct() + { + $this->singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); + + parent::__construct(); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensures a single space after language constructs.', + [ + new CodeSample( + <<<'PHP' + [ + 'echo', + ], + ], + ), + new CodeSample( + <<<'PHP' + [ + 'yield_from', + ], + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer. + * Must run after ArraySyntaxFixer, ModernizeStrposFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function configurePostNormalisation(): void + { + $this->singleSpaceAroundConstructFixer->configure([ + 'constructs_contain_a_single_space' => [ + 'yield_from', + ], + 'constructs_preceded_by_a_single_space' => [], + 'constructs_followed_by_a_single_space' => $this->configuration['constructs'], + ]); + } + + protected function createProxyFixers(): array + { + return [$this->singleSpaceAroundConstructFixer]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $defaults = self::TOKEN_MAP; + $tokens = array_keys($defaults); + + unset($defaults['type_colon']); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('constructs', 'List of constructs which must be followed by a single space.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($tokens)]) + ->setDefault(array_keys($defaults)) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php new file mode 100644 index 0000000..f9d4161 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php @@ -0,0 +1,510 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * constructs_contain_a_single_space?: list<'yield_from'>, + * constructs_followed_by_a_single_space?: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'private_set'|'protected'|'protected_set'|'public'|'public_set'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>, + * constructs_preceded_by_a_single_space?: list<'as'|'else'|'elseif'|'use_lambda'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * constructs_contain_a_single_space: list<'yield_from'>, + * constructs_followed_by_a_single_space: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'private_set'|'protected'|'protected_set'|'public'|'public_set'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>, + * constructs_preceded_by_a_single_space: list<'as'|'else'|'elseif'|'use_lambda'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Andreas Möller + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleSpaceAroundConstructFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private const TOKEN_MAP_CONTAIN_A_SINGLE_SPACE = [ + // for now, only one case - but we are ready to extend it, when we learn about new cases to cover + 'yield_from' => \T_YIELD_FROM, + ]; + + /** + * @var array + */ + private const TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE = [ + 'as' => \T_AS, + 'else' => \T_ELSE, + 'elseif' => \T_ELSEIF, + 'use_lambda' => CT::T_USE_LAMBDA, + ]; + + /** + * @var array + */ + private const TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE = [ + 'abstract' => \T_ABSTRACT, + 'as' => \T_AS, + 'attribute' => CT::T_ATTRIBUTE_CLOSE, + 'break' => \T_BREAK, + 'case' => \T_CASE, + 'catch' => \T_CATCH, + 'class' => \T_CLASS, + 'clone' => \T_CLONE, + 'comment' => \T_COMMENT, + 'const' => \T_CONST, + 'const_import' => CT::T_CONST_IMPORT, + 'continue' => \T_CONTINUE, + 'do' => \T_DO, + 'echo' => \T_ECHO, + 'else' => \T_ELSE, + 'elseif' => \T_ELSEIF, + 'enum' => FCT::T_ENUM, + 'extends' => \T_EXTENDS, + 'final' => \T_FINAL, + 'finally' => \T_FINALLY, + 'for' => \T_FOR, + 'foreach' => \T_FOREACH, + 'function' => \T_FUNCTION, + 'function_import' => CT::T_FUNCTION_IMPORT, + 'global' => \T_GLOBAL, + 'goto' => \T_GOTO, + 'if' => \T_IF, + 'implements' => \T_IMPLEMENTS, + 'include' => \T_INCLUDE, + 'include_once' => \T_INCLUDE_ONCE, + 'instanceof' => \T_INSTANCEOF, + 'insteadof' => \T_INSTEADOF, + 'interface' => \T_INTERFACE, + 'match' => FCT::T_MATCH, + 'named_argument' => CT::T_NAMED_ARGUMENT_COLON, + 'namespace' => \T_NAMESPACE, + 'new' => \T_NEW, + 'open_tag_with_echo' => \T_OPEN_TAG_WITH_ECHO, + 'php_doc' => \T_DOC_COMMENT, + 'php_open' => \T_OPEN_TAG, + 'print' => \T_PRINT, + 'private' => \T_PRIVATE, + 'private_set' => FCT::T_PRIVATE_SET, + 'protected' => \T_PROTECTED, + 'protected_set' => FCT::T_PROTECTED_SET, + 'public' => \T_PUBLIC, + 'public_set' => FCT::T_PUBLIC_SET, + 'readonly' => FCT::T_READONLY, + 'require' => \T_REQUIRE, + 'require_once' => \T_REQUIRE_ONCE, + 'return' => \T_RETURN, + 'static' => \T_STATIC, + 'switch' => \T_SWITCH, + 'throw' => \T_THROW, + 'trait' => \T_TRAIT, + 'try' => \T_TRY, + 'type_colon' => CT::T_TYPE_COLON, + 'use' => \T_USE, + 'use_lambda' => CT::T_USE_LAMBDA, + 'use_trait' => CT::T_USE_TRAIT, + 'var' => \T_VAR, + 'while' => \T_WHILE, + 'yield' => \T_YIELD, + 'yield_from' => \T_YIELD_FROM, + ]; + + /** + * @var array + */ + private array $fixTokenMapFollowedByASingleSpace = []; + + /** + * @var array + */ + private array $fixTokenMapContainASingleSpace = []; + + /** + * @var array + */ + private array $fixTokenMapPrecededByASingleSpace = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensures a single space after language constructs.', + [ + new CodeSample( + <<<'PHP' + [ + 'yield_from', + ], + 'constructs_followed_by_a_single_space' => [ + 'yield_from', + ], + ], + ), + new CodeSample( + <<<'PHP' + [ + 'use_lambda', + ], + 'constructs_followed_by_a_single_space' => [ + 'use_lambda', + ], + ], + ), + new CodeSample( + <<<'PHP' + [ + 'echo', + ], + ], + ), + new CodeSample( + <<<'PHP' + [ + 'yield_from', + ], + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer. + * Must run after ArraySyntaxFixer, ModernizeStrposFixer. + */ + public function getPriority(): int + { + return 36; + } + + public function isCandidate(Tokens $tokens): bool + { + $tokenKinds = [ + ...array_values($this->fixTokenMapContainASingleSpace), + ...array_values($this->fixTokenMapPrecededByASingleSpace), + ...array_values($this->fixTokenMapFollowedByASingleSpace), + ]; + + return $tokens->isAnyTokenKindsFound($tokenKinds); + } + + protected function configurePostNormalisation(): void + { + $this->fixTokenMapContainASingleSpace = []; + + foreach ($this->configuration['constructs_contain_a_single_space'] as $key) { + $this->fixTokenMapContainASingleSpace[$key] = self::TOKEN_MAP_CONTAIN_A_SINGLE_SPACE[$key]; + } + + $this->fixTokenMapPrecededByASingleSpace = []; + + foreach ($this->configuration['constructs_preceded_by_a_single_space'] as $key) { + $this->fixTokenMapPrecededByASingleSpace[$key] = self::TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE[$key]; + } + + $this->fixTokenMapFollowedByASingleSpace = []; + + foreach ($this->configuration['constructs_followed_by_a_single_space'] as $key) { + $this->fixTokenMapFollowedByASingleSpace[$key] = self::TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE[$key]; + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['public'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_public'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC; + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['protected'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_protected'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED; + } + + if (isset($this->fixTokenMapFollowedByASingleSpace['private'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_private'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenKindsContainASingleSpace = array_values($this->fixTokenMapContainASingleSpace); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsContainASingleSpace)) { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(\T_YIELD_FROM) + && 'yield from' !== strtolower($token->getContent()) + ) { + $tokens[$index] = new Token([\T_YIELD_FROM, Preg::replace( + '/\s+/', + ' ', + $token->getContent(), + )]); + } + } + } + + $tokenKindsPrecededByASingleSpace = array_values($this->fixTokenMapPrecededByASingleSpace); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsPrecededByASingleSpace)) { + if (!$this->isFullLineCommentBefore($tokens, $index)) { + $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' '); + } + } + } + + $tokenKindsFollowedByASingleSpace = array_values($this->fixTokenMapFollowedByASingleSpace); + + for ($index = $tokens->count() - 2; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($tokenKindsFollowedByASingleSpace)) { + continue; + } + + $whitespaceTokenIndex = $index + 1; + + if ($tokens[$whitespaceTokenIndex]->equalsAny([',', ':', ';', ')', [CT::T_ARRAY_BRACKET_CLOSE], [CT::T_DESTRUCTURING_BRACKET_CLOSE]])) { + continue; + } + + if ( + $token->isGivenKind(\T_STATIC) + && !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind([\T_FN, \T_FUNCTION, \T_NS_SEPARATOR, \T_STRING, \T_VARIABLE, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE]) + ) { + continue; + } + + if ($token->isGivenKind(\T_OPEN_TAG)) { + if ($tokens[$whitespaceTokenIndex]->isGivenKind(\T_WHITESPACE) && !str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n") && !str_contains($token->getContent(), "\n")) { + $tokens->clearAt($whitespaceTokenIndex); + } + + continue; + } + + if ($token->isGivenKind(\T_CLASS) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(')) { + continue; + } + + if ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS]) && $this->isMultilineExtendsOrImplementsWithMoreThanOneAncestor($tokens, $index)) { + continue; + } + + if ($token->isGivenKind(\T_RETURN) && $this->isMultiLineReturn($tokens, $index)) { + continue; + } + + if ($token->isGivenKind(\T_CONST) && $this->isMultilineCommaSeparatedConstant($tokens, $index)) { + continue; + } + + if ($token->isComment() || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + if ($tokens[$whitespaceTokenIndex]->isGivenKind(\T_WHITESPACE) && str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n")) { + continue; + } + } + + if ($tokens[$whitespaceTokenIndex]->isWhitespace() && str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n")) { + $nextNextToken = $tokens[$whitespaceTokenIndex + 1]; + if ( + $nextNextToken->isGivenKind(FCT::T_ATTRIBUTE) + || $nextNextToken->isComment() && str_starts_with($nextNextToken->getContent(), '#[') + ) { + continue; + } + + if ($nextNextToken->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + } + + $tokens->ensureWhitespaceAtIndex($whitespaceTokenIndex, 0, ' '); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $tokenMapContainASingleSpaceKeys = array_keys(self::TOKEN_MAP_CONTAIN_A_SINGLE_SPACE); + $tokenMapPrecededByASingleSpaceKeys = array_keys(self::TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE); + $tokenMapFollowedByASingleSpaceKeys = array_keys(self::TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('constructs_contain_a_single_space', 'List of constructs which must contain a single space.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($tokenMapContainASingleSpaceKeys)]) + ->setDefault($tokenMapContainASingleSpaceKeys) + ->getOption(), + (new FixerOptionBuilder('constructs_preceded_by_a_single_space', 'List of constructs which must be preceded by a single space.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($tokenMapPrecededByASingleSpaceKeys)]) + ->setDefault(['as', 'use_lambda']) + ->getOption(), + (new FixerOptionBuilder('constructs_followed_by_a_single_space', 'List of constructs which must be followed by a single space.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($tokenMapFollowedByASingleSpaceKeys)]) + ->setDefault($tokenMapFollowedByASingleSpaceKeys) + ->getOption(), + ]); + } + + private function isMultiLineReturn(Tokens $tokens, int $index): bool + { + ++$index; + $tokenFollowingReturn = $tokens[$index]; + + if ( + !$tokenFollowingReturn->isGivenKind(\T_WHITESPACE) + || !str_contains($tokenFollowingReturn->getContent(), "\n") + ) { + return false; + } + + $nestedCount = 0; + + for ($indexEnd = \count($tokens) - 1, ++$index; $index < $indexEnd; ++$index) { + if (str_contains($tokens[$index]->getContent(), "\n")) { + return true; + } + + if ($tokens[$index]->equals('{')) { + ++$nestedCount; + } elseif ($tokens[$index]->equals('}')) { + --$nestedCount; + } elseif (0 === $nestedCount && $tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) { + break; + } + } + + return false; + } + + private function isMultilineExtendsOrImplementsWithMoreThanOneAncestor(Tokens $tokens, int $index): bool + { + $hasMoreThanOneAncestor = false; + + while (true) { + ++$index; + $token = $tokens[$index]; + + if ($token->equals(',')) { + $hasMoreThanOneAncestor = true; + + continue; + } + + if ($token->equals('{')) { + return false; + } + + if ($hasMoreThanOneAncestor && str_contains($token->getContent(), "\n")) { + return true; + } + } + + return LogicException('Not reachable code was reached.'); // @phpstan-ignore deadCode.unreachable + } + + private function isMultilineCommaSeparatedConstant(Tokens $tokens, int $constantIndex): bool + { + $isMultilineConstant = false; + $hasMoreThanOneConstant = false; + $index = $constantIndex; + while (!$tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) { + ++$index; + + $isMultilineConstant = $isMultilineConstant || str_contains($tokens[$index]->getContent(), "\n"); + + if ($tokens[$index]->equals(',')) { + $hasMoreThanOneConstant = true; + } + + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null !== $blockType && true === $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + } + } + + return $hasMoreThanOneConstant && $isMultilineConstant; + } + + private function isFullLineCommentBefore(Tokens $tokens, int $index): bool + { + $beforeIndex = $tokens->getPrevNonWhitespace($index); + + if (!$tokens[$beforeIndex]->isGivenKind(\T_COMMENT)) { + return false; + } + + $content = $tokens[$beforeIndex]->getContent(); + + return str_starts_with($content, '#') || str_starts_with($content, '//'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php new file mode 100644 index 0000000..6f60b97 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ListNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * syntax?: 'long'|'short', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * syntax: 'long'|'short', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ListSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private ?int $candidateTokenKind = null; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'List (`array` destructuring) assignment should be declared using the configured syntax.', + [ + new CodeSample( + " 'long'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + + protected function configurePostNormalisation(): void + { + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_BRACKET_OPEN : \T_LIST; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { + if (\T_LIST === $this->candidateTokenKind) { + $this->fixToShortSyntax($tokens, $index); + } else { + $this->fixToLongSyntax($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` syntax for array destructuring.')) + ->setAllowedValues(['long', 'short']) + ->setDefault('short') + ->getOption(), + ]); + } + + private function fixToLongSyntax(Tokens $tokens, int $index): void + { + $closeIndex = $tokens->getNextTokenOfKind($index, [ + [CT::T_DESTRUCTURING_BRACKET_CLOSE], + '[', // [CT::T_ARRAY_BRACKET_OPEN], + ]); + if (!$tokens[$closeIndex]->isGivenKind(CT::T_DESTRUCTURING_BRACKET_CLOSE)) { + return; + } + + $tokens[$index] = new Token('('); + $tokens[$closeIndex] = new Token(')'); + $tokens->insertAt($index, new Token([\T_LIST, 'list'])); + } + + private function fixToShortSyntax(Tokens $tokens, int $index): void + { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DESTRUCTURING_BRACKET_OPEN, '[']); + $tokens[$closeIndex] = new Token([CT::T_DESTRUCTURING_BRACKET_CLOSE, ']']); + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php new file mode 100644 index 0000000..562324f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlankLineAfterNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST be one blank line after the namespace declaration.', + [ + new CodeSample("isTokenKindFound(\T_NAMESPACE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lastIndex = $tokens->count() - 1; + + for ($index = $lastIndex; $index >= 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_NAMESPACE)) { + continue; + } + + $semicolonIndex = $tokens->getNextTokenOfKind($index, [';', '{', [\T_CLOSE_TAG]]); + $semicolonToken = $tokens[$semicolonIndex]; + + if (!$semicolonToken->equals(';')) { + continue; + } + + $indexToEnsureBlankLineAfter = $this->getIndexToEnsureBlankLineAfter($tokens, $semicolonIndex); + $indexToEnsureBlankLine = $tokens->getNonEmptySibling($indexToEnsureBlankLineAfter, 1); + + if (null !== $indexToEnsureBlankLine && $tokens[$indexToEnsureBlankLine]->isWhitespace()) { + $tokens[$indexToEnsureBlankLine] = $this->getTokenToInsert($tokens[$indexToEnsureBlankLine]->getContent(), $indexToEnsureBlankLine === $lastIndex); + } else { + $tokens->insertAt($indexToEnsureBlankLineAfter + 1, $this->getTokenToInsert('', $indexToEnsureBlankLineAfter === $lastIndex)); + } + } + } + + private function getIndexToEnsureBlankLineAfter(Tokens $tokens, int $index): int + { + $indexToEnsureBlankLine = $index; + $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); + + while (null !== $nextIndex) { + $token = $tokens[$nextIndex]; + + if ($token->isWhitespace()) { + if (Preg::match('/\R/', $token->getContent())) { + break; + } + $nextNextIndex = $tokens->getNonEmptySibling($nextIndex, 1); + + if (!$tokens[$nextNextIndex]->isComment()) { + break; + } + } + + if (!$token->isWhitespace() && !$token->isComment()) { + break; + } + + $indexToEnsureBlankLine = $nextIndex; + $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); + } + + return $indexToEnsureBlankLine; + } + + private function getTokenToInsert(string $currentContent, bool $isLastIndex): Token + { + $ending = $this->whitespacesConfig->getLineEnding(); + + $emptyLines = $isLastIndex ? $ending : $ending.$ending; + $indent = Preg::match('/^.*\R( *)$/s', $currentContent, $matches) ? $matches[1] : ''; + + return new Token([\T_WHITESPACE, $emptyLines.$indent]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php new file mode 100644 index 0000000..23827f7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,239 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * max_line_breaks?: int, + * min_line_breaks?: int, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * max_line_breaks: int, + * min_line_breaks: int, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlankLinesBeforeNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Controls blank lines before a namespace declaration.', + [ + new CodeSample(" 1]), + new CodeSample(" 2]), + new CodeSample(" 2]), + new CodeSample(" 0, 'max_line_breaks' => 0]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + + /** + * {@inheritdoc} + * + * Must run after BlankLineAfterOpeningTagFixer, HeaderCommentFixer. + */ + public function getPriority(): int + { + return -31; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('min_line_breaks', 'Minimum line breaks that should exist before namespace declaration.')) + ->setAllowedTypes(['int']) + ->setDefault(2) + ->setNormalizer(static function (Options $options, int $value): int { + if ($value < 0) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `min_line_breaks` cannot be lower than 0.', + ); + } + + return $value; + }) + ->getOption(), + (new FixerOptionBuilder('max_line_breaks', 'Maximum line breaks that should exist before namespace declaration.')) + ->setAllowedTypes(['int']) + ->setDefault(2) + ->setNormalizer(static function (Options $options, int $value): int { + if ($value < 0) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `max_line_breaks` cannot be lower than 0.', + ); + } + + if ($value < $options['min_line_breaks']) { + throw new InvalidFixerConfigurationException( + (new self())->getName(), + 'Option `max_line_breaks` cannot have lower value than `min_line_breaks`.', + ); + } + + return $value; + }) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_NAMESPACE)) { + $this->fixLinesBeforeNamespace( + $tokens, + $index, + $this->configuration['min_line_breaks'], + $this->configuration['max_line_breaks'], + ); + } + } + } + + /** + * Make sure # of line breaks prefixing namespace is within given range. + * + * @param int $expectedMin min. # of line breaks + * @param int $expectedMax max. # of line breaks + */ + protected function fixLinesBeforeNamespace(Tokens $tokens, int $index, int $expectedMin, int $expectedMax): void + { + // Let's determine the total numbers of new lines before the namespace + // and the opening token + $openingTokenIndex = null; + $precedingNewlines = 0; + $newlineInOpening = false; + $openingToken = null; + + for ($i = 1; $i <= 2; ++$i) { + if (isset($tokens[$index - $i])) { + $token = $tokens[$index - $i]; + + if ($token->isGivenKind(\T_OPEN_TAG)) { + $openingToken = $token; + $openingTokenIndex = $index - $i; + $newlineInOpening = str_contains($token->getContent(), "\n"); + + if ($newlineInOpening) { + ++$precedingNewlines; + } + + break; + } + + if (false === $token->isGivenKind(\T_WHITESPACE)) { + break; + } + + $precedingNewlines += substr_count($token->getContent(), "\n"); + } + } + + if ($precedingNewlines >= $expectedMin && $precedingNewlines <= $expectedMax) { + return; + } + + $previousIndex = $index - 1; + $previous = $tokens[$previousIndex]; + + if (0 === $expectedMax) { + // Remove all the previous new lines + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + + // Remove new lines in opening token + if ($newlineInOpening) { + $tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, rtrim($openingToken->getContent()).' ']); + } + + return; + } + + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + // Allow only as many line breaks as configured: + // - keep as-is when current preceding line breaks are within configured range + // - use configured max line breaks if currently there is more preceding line breaks + // - use configured min line breaks if currently there is less preceding line breaks + $newlinesForWhitespaceToken = $precedingNewlines >= $expectedMax + ? $expectedMax + : max($precedingNewlines, $expectedMin); + + if (null !== $openingToken) { + // Use the configured line ending for the PHP opening tag + $content = rtrim($openingToken->getContent()); + $newContent = $content.$lineEnding; + $tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, $newContent]); + --$newlinesForWhitespaceToken; + } + + if (0 === $newlinesForWhitespaceToken) { + // We have all the needed new lines in the opening tag + if ($previous->isWhitespace()) { + // Let's remove the previous token containing extra new lines + $tokens->clearAt($previousIndex); + } + + return; + } + + if ($previous->isWhitespace()) { + // Fix the previous whitespace token + $content = $previous->getContent(); + $pos = strrpos($content, "\n"); + $content = false === $pos ? '' : substr($content, $pos + 1); + $tokens[$previousIndex] = new Token([\T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken).$content]); + } else { + // Add a new whitespace token + $tokens->insertAt($index, new Token([\T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken)])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php new file mode 100644 index 0000000..2cb05a3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CleanNamespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + $samples = []; + + foreach (['namespace Foo \ Bar;', 'echo foo /* comment */ \ bar();'] as $sample) { + $samples[] = new VersionSpecificCodeSample( + "isTokenKindFound(\T_NS_SEPARATOR); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitDataProviderReturnTypeFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $count = $tokens->count(); + + for ($index = 0; $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) { + $previousIndex = $tokens->getPrevMeaningfulToken($index); + + $index = $this->fixNamespace( + $tokens, + $tokens[$previousIndex]->isGivenKind(\T_STRING) ? $previousIndex : $index, + ); + } + } + } + + /** + * @param int $index start of namespace + */ + private function fixNamespace(Tokens $tokens, int $index): int + { + $tillIndex = $index; + + // go to the end of the namespace + while ($tokens[$tillIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) { + $tillIndex = $tokens->getNextMeaningfulToken($tillIndex); + } + + $tillIndex = $tokens->getPrevMeaningfulToken($tillIndex); + + $spaceIndices = []; + + for (; $index <= $tillIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_WHITESPACE)) { + $spaceIndices[] = $index; + } elseif ($tokens[$index]->isComment()) { + $tokens->clearAt($index); + } + } + + if ($tokens[$index - 1]->isWhitespace()) { + array_pop($spaceIndices); + } + + foreach ($spaceIndices as $i) { + $tokens->clearAt($i); + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php new file mode 100644 index 0000000..d8e54d6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 0, 'max_line_breaks' => 1] + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoBlankLinesBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be no blank lines before a namespace declaration.', + [ + new CodeSample( + "configure([ + 'min_line_breaks' => 0, + 'max_line_breaks' => 1, + ]); + + return [ + $blankLineBeforeNamespace, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php new file mode 100644 index 0000000..bbe838c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Bram Gotink + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoLeadingNamespaceWhitespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The namespace declaration line shouldn\'t contain leading whitespace.', + [ + new CodeSample( + <<<'PHP' + isGivenKind(\T_NAMESPACE)) { + continue; + } + + $beforeNamespaceIndex = $index - 1; + $beforeNamespace = $tokens[$beforeNamespaceIndex]; + + if (!$beforeNamespace->isWhitespace()) { + if (!self::endsWithWhitespace($beforeNamespace->getContent())) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding()])); + } + + continue; + } + + $lastNewline = strrpos($beforeNamespace->getContent(), "\n"); + + if (false === $lastNewline) { + $beforeBeforeNamespace = $tokens[$index - 2]; + + if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) { + $tokens->clearAt($beforeNamespaceIndex); + } else { + $tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, substr($beforeNamespace->getContent(), 0, $lastNewline + 1)]); + } + } + } + + private static function endsWithWhitespace(string $str): bool + { + if ('' === $str) { + return false; + } + + return '' === trim(substr($str, -1)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php new file mode 100644 index 0000000..a8c684c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 2, 'max_line_breaks' => 2] (default) + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleBlankLineBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should be exactly one blank line before a namespace declaration.', + [ + new CodeSample("isTokenKindFound(\T_NAMESPACE); + } + + /** + * {@inheritdoc} + * + * Must run after HeaderCommentFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function createProxyFixers(): array + { + $blankLineBeforeNamespace = new BlankLinesBeforeNamespaceFixer(); + $blankLineBeforeNamespace->configure([ + 'min_line_breaks' => 2, + 'max_line_breaks' => 2, + ]); + + return [ + $blankLineBeforeNamespace, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php new file mode 100644 index 0000000..1b00009 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php @@ -0,0 +1,232 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Naming; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Fred Cox + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoHomoglyphNamesFixer extends AbstractFixer +{ + /** + * Used the program https://github.com/mcfedr/homoglyph-download + * to generate this list from + * http://homoglyphs.net/?text=abcdefghijklmnopqrstuvwxyz&lang=en&exc7=1&exc8=1&exc13=1&exc14=1. + * + * Symbols replaced include + * - Latin homoglyphs + * - IPA extensions + * - Greek and Coptic + * - Cyrillic + * - Cyrillic Supplement + * - Letterlike Symbols + * - Latin Numbers + * - Fullwidth Latin + * + * This is not the complete list of unicode homographs, but limited + * to those you are more likely to have typed/copied by accident + * + * @var array + */ + private const REPLACEMENTS = [ + 'O' => '0', + '0' => '0', + 'I' => '1', + '1' => '1', + '2' => '2', + '3' => '3', + '4' => '4', + '5' => '5', + '6' => '6', + '7' => '7', + '8' => '8', + '9' => '9', + 'Α' => 'A', + 'А' => 'A', + 'A' => 'A', + 'ʙ' => 'B', + 'Β' => 'B', + 'В' => 'B', + 'B' => 'B', + 'Ϲ' => 'C', + 'С' => 'C', + 'Ⅽ' => 'C', + 'C' => 'C', + 'Ⅾ' => 'D', + 'D' => 'D', + 'Ε' => 'E', + 'Е' => 'E', + 'E' => 'E', + 'Ϝ' => 'F', + 'F' => 'F', + 'ɢ' => 'G', + 'Ԍ' => 'G', + 'G' => 'G', + 'ʜ' => 'H', + 'Η' => 'H', + 'Н' => 'H', + 'H' => 'H', + 'l' => 'I', + 'Ι' => 'I', + 'І' => 'I', + 'Ⅰ' => 'I', + 'I' => 'I', + 'Ј' => 'J', + 'J' => 'J', + 'Κ' => 'K', + 'К' => 'K', + 'K' => 'K', + 'K' => 'K', + 'ʟ' => 'L', + 'Ⅼ' => 'L', + 'L' => 'L', + 'Μ' => 'M', + 'М' => 'M', + 'Ⅿ' => 'M', + 'M' => 'M', + 'ɴ' => 'N', + 'Ν' => 'N', + 'N' => 'N', + 'Ο' => 'O', + 'О' => 'O', + 'O' => 'O', + 'Ρ' => 'P', + 'Р' => 'P', + 'P' => 'P', + 'Q' => 'Q', + 'ʀ' => 'R', + 'R' => 'R', + 'Ѕ' => 'S', + 'S' => 'S', + 'Τ' => 'T', + 'Т' => 'T', + 'T' => 'T', + 'U' => 'U', + 'Ѵ' => 'V', + 'Ⅴ' => 'V', + 'V' => 'V', + 'W' => 'W', + 'Χ' => 'X', + 'Х' => 'X', + 'Ⅹ' => 'X', + 'X' => 'X', + 'ʏ' => 'Y', + 'Υ' => 'Y', + 'Ү' => 'Y', + 'Y' => 'Y', + 'Ζ' => 'Z', + 'Z' => 'Z', + '_' => '_', + 'ɑ' => 'a', + 'а' => 'a', + 'a' => 'a', + 'Ь' => 'b', + 'b' => 'b', + 'ϲ' => 'c', + 'с' => 'c', + 'ⅽ' => 'c', + 'c' => 'c', + 'ԁ' => 'd', + 'ⅾ' => 'd', + 'd' => 'd', + 'е' => 'e', + 'e' => 'e', + 'f' => 'f', + 'ɡ' => 'g', + 'g' => 'g', + 'һ' => 'h', + 'h' => 'h', + 'ɩ' => 'i', + 'і' => 'i', + 'ⅰ' => 'i', + 'i' => 'i', + 'ј' => 'j', + 'j' => 'j', + 'k' => 'k', + 'ⅼ' => 'l', + 'l' => 'l', + 'ⅿ' => 'm', + 'm' => 'm', + 'n' => 'n', + 'ο' => 'o', + 'о' => 'o', + 'o' => 'o', + 'р' => 'p', + 'p' => 'p', + 'q' => 'q', + 'r' => 'r', + 'ѕ' => 's', + 's' => 's', + 't' => 't', + 'u' => 'u', + 'ν' => 'v', + 'ѵ' => 'v', + 'ⅴ' => 'v', + 'v' => 'v', + 'ѡ' => 'w', + 'w' => 'w', + 'х' => 'x', + 'ⅹ' => 'x', + 'x' => 'x', + 'у' => 'y', + 'y' => 'y', + 'z' => 'z', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace accidental usage of homoglyphs (non ascii characters) in names.', + [new CodeSample("isAnyTokenKindsFound([\T_VARIABLE, \T_STRING]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind([\T_VARIABLE, \T_STRING])) { + continue; + } + + $replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static fn (array $matches): string => self::REPLACEMENTS[$matches[0]] ?? $matches[0], $token->getContent(), -1, $count); + + if ($count > 0) { + $tokens->offsetSet($index, new Token([$token->getId(), $replaced])); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php new file mode 100644 index 0000000..0540a59 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractShortOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AssignNullCoalescingToCoalesceEqualFixer extends AbstractShortOperatorFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use the null coalescing assignment operator `??=` where possible.', + [ + new CodeSample( + "isTokenKindFound(\T_COALESCE); + } + + protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(\T_COALESCE)) { + return false; + } + + // make sure after '??' does not contain '? :' + + $nextIndex = $tokens->getNextTokenOfKind($index, ['?', ';', [\T_CLOSE_TAG]]); + + return !$tokens[$nextIndex]->equals('?'); + } + + protected function getReplacementToken(Token $token): Token + { + return new Token([\T_COALESCE_EQUAL, '??=']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php new file mode 100644 index 0000000..e2d37ad --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php @@ -0,0 +1,995 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * default?: 'align'|'align_by_scope'|'align_single_space'|'align_single_space_by_scope'|'align_single_space_minimal'|'align_single_space_minimal_by_scope'|'at_least_single_space'|'no_space'|'single_space'|null, + * operators?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * default: 'align'|'align_by_scope'|'align_single_space'|'align_single_space_by_scope'|'align_single_space_minimal'|'align_single_space_minimal_by_scope'|'at_least_single_space'|'no_space'|'single_space'|null, + * operators: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BinaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const SINGLE_SPACE = 'single_space'; + + /** + * @internal + */ + public const AT_LEAST_SINGLE_SPACE = 'at_least_single_space'; + + /** + * @internal + */ + public const NO_SPACE = 'no_space'; + + /** + * @internal + */ + public const ALIGN = 'align'; + + /** + * @internal + */ + public const ALIGN_BY_SCOPE = 'align_by_scope'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE = 'align_single_space'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_BY_SCOPE = 'align_single_space_by_scope'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL = 'align_single_space_minimal'; + + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE = 'align_single_space_minimal_by_scope'; + + /** + * Placeholder used as anchor for right alignment. + * + * @internal + */ + public const ALIGN_PLACEHOLDER = "\x2 ALIGNABLE%d \x3"; + + /** + * @var non-empty-list + */ + private const SUPPORTED_OPERATORS = [ + '=', + '*', + '/', + '%', + '<', + '>', + '|', + '^', + '+', + '-', + '&', + '&=', + '&&', + '||', + '.=', + '/=', + '=>', + '==', + '>=', + '===', + '!=', + '<>', + '!==', + '<=', + 'and', + 'or', + 'xor', + '-=', + '%=', + '*=', + '|=', + '+=', + '<<', + '<<=', + '>>', + '>>=', + '^=', + '**', + '**=', + '<=>', + '??', + '??=', + ]; + + /** + * @var non-empty-list + */ + private const ALLOWED_VALUES = [ + self::ALIGN, + self::ALIGN_BY_SCOPE, + self::ALIGN_SINGLE_SPACE, + self::ALIGN_SINGLE_SPACE_MINIMAL, + self::ALIGN_SINGLE_SPACE_BY_SCOPE, + self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE, + self::SINGLE_SPACE, + self::NO_SPACE, + self::AT_LEAST_SINGLE_SPACE, + null, + ]; + + /** + * Keep track of the deepest level ever achieved while + * parsing the code. Used later to replace alignment + * placeholders with spaces. + */ + private int $deepestLevel; + + /** + * Level counter of the current nest level. + * So one level alignments are not mixed with + * other level ones. + */ + private int $currentLevel; + + private TokensAnalyzer $tokensAnalyzer; + + /** + * @var array + */ + private array $alignOperatorTokens = []; + + /** + * @var array + */ + private array $operators = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Binary operators should be surrounded by space as configured.', + [ + new CodeSample( + <<<'PHP' + ['=' => self::ALIGN, 'xor' => null]], + ), + new CodeSample( + <<<'PHP' + ['+=' => self::ALIGN_SINGLE_SPACE]], + ), + new CodeSample( + <<<'PHP' + ['===' => self::ALIGN_SINGLE_SPACE_MINIMAL]], + ), + new CodeSample( + <<<'PHP' + ['|' => self::NO_SPACE]], + ), + new CodeSample( + <<<'PHP' + 1, + "baaaaaaaaaaar" => 11, + ]; + + PHP, + ['operators' => ['=>' => self::SINGLE_SPACE]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN_BY_SCOPE]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN_SINGLE_SPACE]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_BY_SCOPE]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_MINIMAL]], + ), + new CodeSample( + <<<'PHP' + 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, + ]; + + PHP, + ['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE]], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after ArrayIndentationFixer, ArraySyntaxFixer, AssignNullCoalescingToCoalesceEqualFixer, ListSyntaxFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUnsetCastFixer, PowToExponentiationFixer, StandardizeNotEqualsFixer, StrictComparisonFixer. + */ + public function getPriority(): int + { + return -32; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->operators = $this->resolveOperatorsFromConfig(); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + // last and first tokens cannot be an operator + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if (!$this->tokensAnalyzer->isBinaryOperator($index)) { + continue; + } + + if ('=' === $tokens[$index]->getContent()) { + $isDeclare = $this->isEqualPartOfDeclareStatement($tokens, $index); + if (false === $isDeclare) { + $this->fixWhiteSpaceAroundOperator($tokens, $index); + } else { + $index = $isDeclare; // skip `declare(foo ==bar)`, see `declare_equal_normalize` + } + } else { + $this->fixWhiteSpaceAroundOperator($tokens, $index); + } + + // previous of binary operator is now never an operator / previous of declare statement cannot be an operator + --$index; + } + + if (\count($this->alignOperatorTokens) > 0) { + $this->fixAlignment($tokens, $this->alignOperatorTokens); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('default', 'Default fix strategy.')) + ->setDefault(self::SINGLE_SPACE) + ->setAllowedValues(self::ALLOWED_VALUES) + ->getOption(), + (new FixerOptionBuilder('operators', 'Dictionary of `binary operator` => `fix strategy` values that differ from the default strategy. Supported are: '.Utils::naturalLanguageJoinWithBackticks(self::SUPPORTED_OPERATORS).'.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option): bool { + foreach ($option as $operator => $value) { + if (!\in_array($operator, self::SUPPORTED_OPERATORS, true)) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected "operators" key, expected any of %s, got "%s".', + Utils::naturalLanguageJoin(self::SUPPORTED_OPERATORS), + \gettype($operator).'#'.$operator, + ), + ); + } + + if (!\in_array($value, self::ALLOWED_VALUES, true)) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected value for operator "%s", expected any of %s, got "%s".', + $operator, + Utils::naturalLanguageJoin(array_map( + static fn ($value): string => Utils::toString($value), + self::ALLOWED_VALUES, + )), + \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value), + ), + ); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + ]); + } + + private function fixWhiteSpaceAroundOperator(Tokens $tokens, int $index): void + { + $tokenContent = strtolower($tokens[$index]->getContent()); + + if (!\array_key_exists($tokenContent, $this->operators)) { + return; // not configured to be changed + } + + if (self::SINGLE_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToSingleSpace($tokens, $index); + + return; + } + + if (self::AT_LEAST_SINGLE_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToAtLeastSingleSpace($tokens, $index); + + return; + } + + if (self::NO_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToNoSpace($tokens, $index); + + return; + } + + // schedule for alignment + $this->alignOperatorTokens[$tokenContent] = $this->operators[$tokenContent]; + + if ( + self::ALIGN === $this->operators[$tokenContent] + || self::ALIGN_BY_SCOPE === $this->operators[$tokenContent] + ) { + return; + } + + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + if ( + self::ALIGN_SINGLE_SPACE_MINIMAL === $this->operators[$tokenContent] + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $this->operators[$tokenContent] + ) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + + return; + } + + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + private function fixWhiteSpaceAroundOperatorToSingleSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } + } + + private function fixWhiteSpaceAroundOperatorToAtLeastSingleSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if (!$tokens[$index + 1]->isWhitespace()) { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + // fix white space before operator + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } + } + + private function fixWhiteSpaceAroundOperatorToNoSpace(Tokens $tokens, int $index): void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (!str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens->clearAt($index + 1); + } + } + + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (!str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } + + /** + * @return false|int index of T_DECLARE where the `=` belongs to or `false` + */ + private function isEqualPartOfDeclareStatement(Tokens $tokens, int $index) + { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevMeaningfulIndex]->isGivenKind(\T_STRING)) { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); + if ($tokens[$prevMeaningfulIndex]->equals('(')) { + $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex); + if ($tokens[$prevMeaningfulIndex]->isGivenKind(\T_DECLARE)) { + return $prevMeaningfulIndex; + } + } + } + + return false; + } + + /** + * @return array + */ + private function resolveOperatorsFromConfig(): array + { + $operators = []; + + if (null !== $this->configuration['default']) { + foreach (self::SUPPORTED_OPERATORS as $operator) { + $operators[$operator] = $this->configuration['default']; + } + } + + foreach ($this->configuration['operators'] as $operator => $value) { + if (null === $value) { + unset($operators[$operator]); + } else { + $operators[$operator] = $value; + } + } + + return $operators; + } + + // Alignment logic related methods + + /** + * @param array $toAlign + */ + private function fixAlignment(Tokens $tokens, array $toAlign): void + { + $this->deepestLevel = 0; + $this->currentLevel = 0; + + foreach ($toAlign as $tokenContent => $alignStrategy) { + // This fixer works partially on Tokens and partially on string representation of code. + // During the process of fixing internal state of single Token may be affected by injecting ALIGN_PLACEHOLDER to its content. + // The placeholder will be resolved by `replacePlaceholders` method by removing placeholder or changing it into spaces. + // That way of fixing the code causes disturbances in marking Token as changed - if code is perfectly valid then placeholder + // still be injected and removed, which will cause the `changed` flag to be set. + // To handle that unwanted behaviour we work on clone of Tokens collection and then override original collection with fixed collection. + $tokensClone = clone $tokens; + + if ('=>' === $tokenContent) { + $this->injectAlignmentPlaceholdersForArrow($tokensClone, 0, \count($tokens)); + } else { + $this->injectAlignmentPlaceholdersDefault($tokensClone, 0, \count($tokens), $tokenContent); + } + + // for all tokens that should be aligned but do not have anything to align with, fix spacing if needed + if ( + self::ALIGN_SINGLE_SPACE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy + || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy + ) { + if ('=>' === $tokenContent) { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_DOUBLE_ARROW)) { // always binary operator, never part of declare statement + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } elseif ('=' === $tokenContent) { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if ('=' === $tokens[$index]->getContent() && false === $this->isEqualPartOfDeclareStatement($tokens, $index) && $this->tokensAnalyzer->isBinaryOperator($index)) { + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } else { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + $content = $tokens[$index]->getContent(); + if (strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index)) { // never part of declare statement + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } + } + + $tokens->setCode($this->replacePlaceholders($tokensClone, $alignStrategy, $tokenContent)); + } + } + + private function injectAlignmentPlaceholdersDefault(Tokens $tokens, int $startAt, int $endAt, string $tokenContent): void + { + $newLineFoundSinceLastPlaceholder = true; + + for ($index = $startAt; $index < $endAt; ++$index) { + $token = $tokens[$index]; + $content = $token->getContent(); + + if (str_contains($content, "\n")) { + $newLineFoundSinceLastPlaceholder = true; + } + + if ( + strtolower($content) === $tokenContent + && $this->tokensAnalyzer->isBinaryOperator($index) + && ('=' !== $content || false === $this->isEqualPartOfDeclareStatement($tokens, $index)) + && $newLineFoundSinceLastPlaceholder + ) { + $tokens[$index] = new Token(\sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$content); + $newLineFoundSinceLastPlaceholder = false; + + continue; + } + + if ($token->isGivenKind(\T_FN)) { + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index); + $this->injectAlignmentPlaceholders($tokens, $from + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->isGivenKind([\T_FUNCTION, \T_CLASS])) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';', '(']); + // We don't align `=` on multi-line definition of function parameters with default values + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($tokens[$index]->equals(';')) { + continue; + } + + // Update the token to the `{` one in order to apply the following logic + $token = $tokens[$index]; + } + + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + + if ($token->equals('[')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACKET, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + + continue; + } + } + } + + private function injectAlignmentPlaceholders(Tokens $tokens, int $from, int $until, string $tokenContent): void + { + // Only inject placeholders for multi-line code + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersDefault($tokens, $from, $until, $tokenContent); + $this->currentLevel = $currentLevel; + } + } + + private function injectAlignmentPlaceholdersForArrow(Tokens $tokens, int $startAt, int $endAt): void + { + $newLineFoundSinceLastPlaceholder = true; + $yieldFoundSinceLastPlaceholder = false; + + for ($index = $startAt; $index < $endAt; ++$index) { + $token = $tokens[$index]; + $content = $token->getContent(); + + if (str_contains($content, "\n")) { + $newLineFoundSinceLastPlaceholder = true; + } + + if ($token->isGivenKind(\T_YIELD)) { + $yieldFoundSinceLastPlaceholder = true; + } + + if ($token->isGivenKind(\T_FN)) { + $yieldFoundSinceLastPlaceholder = false; + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index); + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + $index = $until; + + continue; + } + + if ($token->isGivenKind(\T_ARRAY)) { // don't use "$tokens->isArray()" here, short arrays are handled in the next case + $yieldFoundSinceLastPlaceholder = false; + $from = $tokens->getNextMeaningfulToken($index); + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $from); + $index = $until; + + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $yieldFoundSinceLastPlaceholder = false; + $from = $index; + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $from); + $index = $until; + + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + + continue; + } + + // no need to analyse for `isBinaryOperator` (always true), nor if part of declare statement (not valid PHP) + // there is also no need to analyse the second arrow of a line + if ($token->isGivenKind(\T_DOUBLE_ARROW) && $newLineFoundSinceLastPlaceholder) { + if ($yieldFoundSinceLastPlaceholder) { + $this->currentLevel = ++$this->deepestLevel; + } + $tokenContent = \sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$token->getContent(); + + $nextToken = $tokens[$index + 1]; + if (!$nextToken->isWhitespace()) { + $tokenContent .= ' '; + } elseif ($nextToken->isWhitespace(" \t")) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + + $tokens[$index] = new Token([\T_DOUBLE_ARROW, $tokenContent]); + $newLineFoundSinceLastPlaceholder = false; + $yieldFoundSinceLastPlaceholder = false; + + continue; + } + + if ($token->equals(';')) { + ++$this->deepestLevel; + ++$this->currentLevel; + + continue; + } + + if ($token->equals(',')) { + for ($i = $index; $i < $endAt - 1; ++$i) { + if (str_contains($tokens[$i - 1]->getContent(), "\n")) { + $newLineFoundSinceLastPlaceholder = true; + + break; + } + + if ($tokens[$i + 1]->isGivenKind(\T_DOUBLE_ARROW)) { + break; + } + + if ($tokens[$i + 1]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN])) { + $arrayStartIndex = $tokens[$i + 1]->isGivenKind(\T_ARRAY) + ? $tokens->getNextMeaningfulToken($i + 1) + : $i + 1; + $blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]); + $arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex); + + if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) { + break; + } + } + + ++$index; + } + } + + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + + continue; + } + + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + + continue; + } + } + } + + private function injectArrayAlignmentPlaceholders(Tokens $tokens, int $from, int $until): void + { + // Only inject placeholders for multi-line arrays + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersForArrow($tokens, $from, $until); + $this->currentLevel = $currentLevel; + } + } + + private function fixWhiteSpaceBeforeOperator(Tokens $tokens, int $index, string $alignStrategy): void + { + // fix white space after operator is not needed as BinaryOperatorSpacesFixer took care of this (if strategy is _not_ ALIGN) + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + + return; + } + + if ( + self::ALIGN_SINGLE_SPACE_MINIMAL !== $alignStrategy && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy + || $tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment() + ) { + return; + } + + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n")) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']); + } + } + + /** + * Look for group of placeholders and provide vertical alignment. + */ + private function replacePlaceholders(Tokens $tokens, string $alignStrategy, string $tokenContent): string + { + $tmpCode = $tokens->generateCode(); + + for ($j = 0; $j <= $this->deepestLevel; ++$j) { + $placeholder = \sprintf(self::ALIGN_PLACEHOLDER, $j); + + if (!str_contains($tmpCode, $placeholder)) { + continue; + } + + $lines = explode("\n", $tmpCode); + $groups = []; + $groupIndex = 0; + $groups[$groupIndex] = []; + + foreach ($lines as $index => $line) { + if (substr_count($line, $placeholder) > 0) { + $groups[$groupIndex][] = $index; + } elseif ( + self::ALIGN_BY_SCOPE !== $alignStrategy + && self::ALIGN_SINGLE_SPACE_BY_SCOPE !== $alignStrategy + && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy + ) { + ++$groupIndex; + $groups[$groupIndex] = []; + } + } + + foreach ($groups as $group) { + if (\count($group) < 1) { + continue; + } + + if (self::ALIGN !== $alignStrategy) { + // move placeholders to match strategy + foreach ($group as $index) { + \assert(isset($lines[$index])); + $currentPosition = strpos($lines[$index], $placeholder); + \assert(false !== $currentPosition); + $before = substr($lines[$index], 0, $currentPosition); + + if ( + self::ALIGN_SINGLE_SPACE === $alignStrategy + || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy + ) { + if (!str_ends_with($before, ' ')) { // if last char of before-content is not ' '; add it + $before .= ' '; + } + } elseif ( + self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy + || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy + ) { + if (!Preg::match('/^\h+$/', $before)) { // if indent; do not move, leave to other fixer + $before = rtrim($before).' '; + } + } + + $lines[$index] = $before.substr($lines[$index], $currentPosition); + } + } + + $rightmostSymbol = 0; + foreach ($group as $index) { + \assert(isset($lines[$index])); + $rightmostSymbol = max($rightmostSymbol, $this->getSubstringWidth($lines[$index], $placeholder)); + } + + foreach ($group as $index) { + \assert(isset($lines[$index])); + $line = $lines[$index]; + $currentSymbol = $this->getSubstringWidth($line, $placeholder); + $delta = abs($rightmostSymbol - $currentSymbol); + + if ($delta > 0) { + $line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line); + $lines[$index] = $line; + } + } + } + + $tmpCode = str_replace($placeholder, '', implode("\n", $lines)); + } + + return $tmpCode; + } + + private function getSubstringWidth(string $haystack, string $needle): int + { + $position = strpos($haystack, $needle); + \assert(\is_int($position)); + + $substring = substr($haystack, 0, $position); + + return mb_strwidth($substring); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php new file mode 100644 index 0000000..2f6820c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php @@ -0,0 +1,162 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * spacing?: 'none'|'one', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * spacing: 'none'|'one', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ConcatSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Concatenation should be spaced according to configuration.', + [ + new CodeSample( + " 'none'], + ), + new CodeSample( + " 'one'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoUnneededControlParenthesesFixer, SingleLineThrowFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('.'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->equals('.')) { + if ('one' === $this->configuration['spacing']) { + $this->fixConcatenationToSingleSpace($tokens, $index); + } else { + $this->fixConcatenationToNoSpace($tokens, $index); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('spacing', 'Spacing to apply around concatenation operator.')) + ->setAllowedValues(['one', 'none']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToNoSpace(Tokens $tokens, int $index): void + { + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + + if (!$prevNonWhitespaceToken->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT]) || str_starts_with($prevNonWhitespaceToken->getContent(), '/*')) { + $tokens->removeLeadingWhitespace($index, " \t"); + } + + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT])) { + $tokens->removeTrailingWhitespace($index, " \t"); + } + } + + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToSingleSpace(Tokens $tokens, int $index): void + { + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1); + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1); + } + + /** + * @param int $index index of concatenation '.' token + * @param int $offset 1 or -1 + */ + private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, int $index, int $offset): void + { + if (-1 !== $offset && 1 !== $offset) { + throw new \InvalidArgumentException(\sprintf( + 'Expected `-1|1` for "$offset", got "%s"', + $offset, + )); + } + + $offsetIndex = $index + $offset; + + if (!$tokens[$offsetIndex]->isWhitespace()) { + $tokens->insertAt($index + (1 === $offset ? 1 : 0), new Token([\T_WHITESPACE, ' '])); + + return; + } + + if (str_contains($tokens[$offsetIndex]->getContent(), "\n")) { + return; + } + + if ($tokens[$index + $offset * 2]->isComment()) { + return; + } + + $tokens[$offsetIndex] = new Token([\T_WHITESPACE, ' ']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php new file mode 100644 index 0000000..f1dafc7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php @@ -0,0 +1,181 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * style?: 'post'|'pre', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * style: 'post'|'pre', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class IncrementStyleFixer extends AbstractIncrementOperatorFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const STYLE_PRE = 'pre'; + + /** + * @internal + */ + public const STYLE_POST = 'post'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Pre- or post-increment and decrement operators should be used if possible.', + [ + new CodeSample(" self::STYLE_POST], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. + * Must run after StandardizeIncrementFixer. + */ + public function getPriority(): int + { + return 15; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_INC, \T_DEC]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Whether to use pre- or post-increment and decrement operators.')) + ->setAllowedValues([self::STYLE_PRE, self::STYLE_POST]) + ->setDefault(self::STYLE_PRE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind([\T_INC, \T_DEC])) { + continue; + } + + if (self::STYLE_PRE === $this->configuration['style'] && $tokensAnalyzer->isUnarySuccessorOperator($index)) { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + if (!$nextToken->equalsAny([';', ')'])) { + continue; + } + + $startIndex = $this->findStart($tokens, $index); + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)]; + + if ($prevToken->equalsAny([';', '{', '}', [\T_OPEN_TAG], ')'])) { + $tokens->clearAt($index); + $tokens->insertAt($startIndex, clone $token); + } + } elseif (self::STYLE_POST === $this->configuration['style'] && $tokensAnalyzer->isUnaryPredecessorOperator($index)) { + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny([';', '{', '}', [\T_OPEN_TAG], ')'])) { + continue; + } + + $endIndex = $this->findEnd($tokens, $index); + $nextToken = $tokens[$tokens->getNextMeaningfulToken($endIndex)]; + + if ($nextToken->equalsAny([';', ')'])) { + $tokens->clearAt($index); + $tokens->insertAt($tokens->getNextNonWhitespace($endIndex), clone $token); + } + } + } + } + + private function findEnd(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + while ($nextToken->equalsAny([ + '$', + '(', + '[', + [CT::T_DYNAMIC_PROP_BRACE_OPEN], + [CT::T_DYNAMIC_VAR_BRACE_OPEN], + [CT::T_ARRAY_INDEX_BRACE_OPEN], + [\T_NS_SEPARATOR], + [\T_STATIC], + [\T_STRING], + [\T_VARIABLE], + ])) { + $blockType = Tokens::detectBlockType($nextToken); + + if (null !== $blockType) { + $nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex); + } + + $index = $nextIndex; + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + } + + if ($nextToken->isObjectOperator()) { + return $this->findEnd($tokens, $nextIndex); + } + + if ($nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + return $this->findEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php new file mode 100644 index 0000000..7a35c3b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Haralan Dobrev + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LogicalOperatorsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use `&&` and `||` logical operators instead of `and` and `or`.', + [ + new CodeSample( + <<<'PHP' + isAnyTokenKindsFound([\T_LOGICAL_AND, \T_LOGICAL_OR]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_LOGICAL_AND)) { + $tokens[$index] = new Token([\T_BOOLEAN_AND, '&&']); + } elseif ($token->isGivenKind(\T_LOGICAL_OR)) { + $tokens[$index] = new Token([\T_BOOLEAN_OR, '||']); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php new file mode 100644 index 0000000..ec5ff40 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LongToShorthandOperatorFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractShortOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-import-type _PhpTokenArray from Token + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LongToShorthandOperatorFixer extends AbstractShortOperatorFixer +{ + /** + * @var non-empty-array + */ + private const OPERATORS = [ + '+' => [\T_PLUS_EQUAL, '+='], + '-' => [\T_MINUS_EQUAL, '-='], + '*' => [\T_MUL_EQUAL, '*='], + '/' => [\T_DIV_EQUAL, '/='], + '&' => [\T_AND_EQUAL, '&='], + '.' => [\T_CONCAT_EQUAL, '.='], + '%' => [\T_MOD_EQUAL, '%='], + '|' => [\T_OR_EQUAL, '|='], + '^' => [\T_XOR_EQUAL, '^='], + ]; + + /** + * @var non-empty-list + */ + private array $operatorTypes; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Shorthand notation for operators should be used if possible.', + [ + new CodeSample("isAnyTokenKindsFound([...array_keys(self::OPERATORS), FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->operatorTypes = array_keys(self::OPERATORS); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + parent::applyFix($file, $tokens); + } + + protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equalsAny($this->operatorTypes)) { + return false; + } + + while (null !== $index) { + $index = $tokens->getNextMeaningfulToken($index); + $otherToken = $tokens[$index]; + + if ($otherToken->equalsAny([';', [\T_CLOSE_TAG]])) { + return true; + } + + // fast precedence check + if ($otherToken->equals('?') || $otherToken->isGivenKind(\T_INSTANCEOF)) { + return false; + } + + $blockType = Tokens::detectBlockType($otherToken); + + if (null !== $blockType) { + if (false === $blockType['isStart']) { + return true; + } + + $index = $tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + // precedence check + if ($this->tokensAnalyzer->isBinaryOperator($index)) { + return false; + } + } + + return false; // unreachable, but keeps SCA happy + } + + protected function getReplacementToken(Token $token): Token + { + \assert(isset(self::OPERATORS[$token->getContent()])); // for PHPStan + + return new Token(self::OPERATORS[$token->getContent()]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewExpressionParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewExpressionParenthesesFixer.php new file mode 100644 index 0000000..1eb01b0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewExpressionParenthesesFixer.php @@ -0,0 +1,241 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * use_parentheses?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * use_parentheses: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Valentin Udaltsov + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NewExpressionParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All `new` expressions with a further call must (not) be wrapped in parentheses.', + [ + new VersionSpecificCodeSample( + "bar();\n", + new VersionSpecification(8_04_00), + ), + new VersionSpecificCodeSample( + "bar();\n", + new VersionSpecification(8_04_00), + ), + new VersionSpecificCodeSample( + "bar();\n", + new VersionSpecification(8_04_00), + ['use_parentheses' => true], + ), + new VersionSpecificCodeSample( + "bar();\n", + new VersionSpecification(8_04_00), + ['use_parentheses' => true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NewWithParenthesesFixer, NoUnneededControlParenthesesFixer. + */ + public function getPriority(): int + { + return 29; + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_04_00 && $tokens->isTokenKindFound(\T_NEW); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('use_parentheses', 'Whether `new` expressions with a further call should be wrapped in parentheses or not.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $useParentheses = $this->configuration['use_parentheses']; + + for ($index = $tokens->count() - 3; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_NEW)) { + continue; + } + + $classStartIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $classStartIndex) { + return; + } + + // anonymous class + if ($tokens[$classStartIndex]->isGivenKind(\T_CLASS)) { + $nextIndex = $tokens->getNextMeaningfulToken($classStartIndex); + + if ($tokens[$nextIndex]->equals('(')) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + } else { + $nextIndex = $classStartIndex; + } + + $bodyStartIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']); + $bodyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $bodyStartIndex); + + if ($useParentheses) { + $this->ensureWrappedInParentheses($tokens, $index, $bodyEndIndex); + } else { + $this->ensureNotWrappedInParentheses($tokens, $index, $bodyEndIndex); + } + + continue; + } + + // named class + $classEndIndex = $this->findClassEndIndex($tokens, $classStartIndex); + + if (null === $classEndIndex) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($classEndIndex); + + if (!$tokens[$nextIndex]->equals('(')) { + // If arguments' parentheses are absent then either this new expression is not further called + // and does not need parentheses, or we cannot omit its parentheses due to the grammar rules. + continue; + } + + $argsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + + if ($useParentheses) { + $this->ensureWrappedInParentheses($tokens, $index, $argsEndIndex); + } else { + $this->ensureNotWrappedInParentheses($tokens, $index, $argsEndIndex); + } + } + } + + private function ensureWrappedInParentheses(Tokens $tokens, int $exprStartIndex, int $exprEndIndex): void + { + $prevIndex = $tokens->getPrevMeaningfulToken($exprStartIndex); + $nextIndex = $tokens->getNextMeaningfulToken($exprEndIndex); + + if ($tokens[$prevIndex]->isGivenKind(CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN) + && $tokens[$nextIndex]->isGivenKind(CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE) + ) { + return; + } + + if (!$tokens[$nextIndex]->isObjectOperator() && !$tokens[$nextIndex]->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + return; + } + + $tokens->insertAt($exprStartIndex, [new Token([CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN, '('])]); + $tokens->insertAt($exprEndIndex + 2, [new Token([CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE, ')'])]); + } + + private function ensureNotWrappedInParentheses(Tokens $tokens, int $exprStartIndex, int $exprEndIndex): void + { + $prevIndex = $tokens->getPrevMeaningfulToken($exprStartIndex); + $nextIndex = $tokens->getNextMeaningfulToken($exprEndIndex); + + if (!$tokens[$prevIndex]->isGivenKind(CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN) + || !$tokens[$nextIndex]->isGivenKind(CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE) + ) { + return; + } + + $operatorIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($nextIndex); + } + + private function findClassEndIndex(Tokens $tokens, int $index): ?int + { + // (expression) class name + if ($tokens[$index]->equals('(')) { + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + } + + // regular class name or $variable class name + $nextTokens = [ + [\T_STRING], + [\T_NS_SEPARATOR], + [CT::T_NAMESPACE_OPERATOR], + [\T_VARIABLE], + '$', + [CT::T_DYNAMIC_VAR_BRACE_OPEN], + '[', + [\T_OBJECT_OPERATOR], + [\T_NULLSAFE_OBJECT_OPERATOR], + [\T_PAAMAYIM_NEKUDOTAYIM], + ]; + + if (!$tokens[$index]->equalsAny($nextTokens)) { + return null; + } + + while ($tokens[$index]->equalsAny($nextTokens)) { + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null !== $blockType) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return $index - 1; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php new file mode 100644 index 0000000..7c9bb38 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * anonymous_class?: bool, + * named_class?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * anonymous_class: bool, + * named_class: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NewWithBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private NewWithParenthesesFixer $newWithParenthesesFixer; + + public function __construct() + { + $this->newWithParenthesesFixer = new NewWithParenthesesFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->newWithParenthesesFixer->getDefinition(); + + return new FixerDefinition( + 'All instances created with `new` keyword must (not) be followed by braces.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassDefinitionFixer. + */ + public function getPriority(): int + { + return $this->newWithParenthesesFixer->getPriority(); + } + + public function getSuccessorsNames(): array + { + return [ + $this->newWithParenthesesFixer->getName(), + ]; + } + + /** + * @param _AutogeneratedInputConfiguration $configuration + */ + protected function configurePreNormalisation(array $configuration): void + { + $this->newWithParenthesesFixer->configure($configuration); + } + + protected function createProxyFixers(): array + { + return [ + $this->newWithParenthesesFixer, + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return $this->newWithParenthesesFixer->createConfigurationDefinition(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php new file mode 100644 index 0000000..18cb519 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithParenthesesFixer.php @@ -0,0 +1,223 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * anonymous_class?: bool, + * named_class?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * anonymous_class: bool, + * named_class: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NewWithParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + private const NEXT_TOKEN_KINDS = [ + '?', + ';', + ',', + '(', + ')', + '[', + ']', + ':', + '<', + '>', + '+', + '-', + '*', + '/', + '%', + '&', + '^', + '|', + [\T_CLASS], + [\T_IS_SMALLER_OR_EQUAL], + [\T_IS_GREATER_OR_EQUAL], + [\T_IS_EQUAL], + [\T_IS_NOT_EQUAL], + [\T_IS_IDENTICAL], + [\T_IS_NOT_IDENTICAL], + [\T_CLOSE_TAG], + [\T_LOGICAL_AND], + [\T_LOGICAL_OR], + [\T_LOGICAL_XOR], + [\T_BOOLEAN_AND], + [\T_BOOLEAN_OR], + [\T_SL], + [\T_SR], + [\T_INSTANCEOF], + [\T_AS], + [\T_DOUBLE_ARROW], + [\T_POW], + [\T_SPACESHIP], + [CT::T_ARRAY_BRACKET_OPEN], + [CT::T_ARRAY_BRACKET_CLOSE], + [CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN], + [CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE], + [FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG], + [FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All instances created with `new` keyword must (not) be followed by parentheses.', + [ + new CodeSample(" false], + ), + new CodeSample( + " false], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassDefinitionFixer, NewExpressionParenthesesFixer. + */ + public function getPriority(): int + { + return 38; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_NEW); + } + + /** + * @protected + * + * @TODO 4.0 move visibility from annotation to code when `NewWithBracesFixer` is removed + */ + public function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('named_class', 'Whether named classes should be followed by parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('anonymous_class', 'Whether anonymous classes should be followed by parentheses.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(false, true)) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 3; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_NEW)) { + continue; + } + + $nextIndex = $tokens->getNextTokenOfKind($index, self::NEXT_TOKEN_KINDS); + + // new anonymous class definition + if ($tokens[$nextIndex]->isGivenKind(\T_CLASS)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (true === $this->configuration['anonymous_class']) { + $this->ensureParenthesesAt($tokens, $nextIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $nextIndex); + } + + continue; + } + + // entrance into array index syntax - need to look for exit + + while ($tokens[$nextIndex]->equals('[') || $tokens[$nextIndex]->isGivenKind(CT::T_ARRAY_INDEX_BRACE_OPEN)) { + $nextIndex = $tokens->findBlockEnd(Tokens::detectBlockType($tokens[$nextIndex])['type'], $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + + if (true === $this->configuration['named_class']) { + $this->ensureParenthesesAt($tokens, $nextIndex); + } else { + $this->ensureNoParenthesesAt($tokens, $nextIndex); + } + } + } + + private function ensureParenthesesAt(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->equals('(') && !$token->isObjectOperator()) { + $tokens->insertAt( + $tokens->getPrevMeaningfulToken($index) + 1, + [new Token('('), new Token(')')], + ); + } + } + + private function ensureNoParenthesesAt(Tokens $tokens, int $index): void + { + if (!$tokens[$index]->equals('(')) { + return; + } + + $closingIndex = $tokens->getNextMeaningfulToken($index); + + // constructor has arguments - parentheses can not be removed + if (!$tokens[$closingIndex]->equals(')')) { + return; + } + + // Check if there's an object operator after the closing parenthesis + // Preserve parentheses in expressions like "new A()->method()" as per RFC + $afterClosingIndex = $tokens->getNextMeaningfulToken($closingIndex); + if ($tokens[$afterClosingIndex]->isObjectOperator()) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php new file mode 100644 index 0000000..f137ec6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSpaceAroundDoubleColonFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no space around double colons (also called Scope Resolution Operator or Paamayim Nekudotayim).', + [new CodeSample("isTokenKindFound(\T_DOUBLE_COLON); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 2; $index > 1; --$index) { + if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + $this->removeSpace($tokens, $index, 1); + $this->removeSpace($tokens, $index, -1); + } + } + } + + /** + * @param -1|1 $direction + */ + private function removeSpace(Tokens $tokens, int $index, int $direction): void + { + if (!$tokens[$index + $direction]->isWhitespace()) { + return; + } + + if ($tokens[$tokens->getNonWhitespaceSibling($index, $direction)]->isComment()) { + return; + } + + $tokens->clearAt($index + $direction); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php new file mode 100644 index 0000000..29e24ac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php @@ -0,0 +1,376 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _ConcatOperandType array{ + * start: int, + * end: int, + * type: self::STR_*, + * } + * @phpstan-type _AutogeneratedInputConfiguration array{ + * juggle_simple_strings?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * juggle_simple_strings: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessConcatOperatorFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const STR_DOUBLE_QUOTE = 0; + private const STR_DOUBLE_QUOTE_VAR = 1; + private const STR_SINGLE_QUOTE = 2; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless concat operations.', + [ + new CodeSample(" true]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before DateTimeCreateFromFormatCallFixer, EregToPregFixer, PhpUnitDedicateAssertInternalTypeFixer, RegularCallableCallFixer, SetTypeToCastFixer. + * Must run after ExplicitStringVariableFixer, NoBinaryStringFixer, SingleQuoteFixer. + */ + public function getPriority(): int + { + return 5; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('.') && $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, '"']); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals('.')) { + continue; + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + + if ($this->containsLinebreak($tokens, $index, $nextMeaningfulTokenIndex)) { + continue; + } + + $secondOperand = $this->getConcatOperandType($tokens, $nextMeaningfulTokenIndex, 1); + + if (null === $secondOperand) { + continue; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($this->containsLinebreak($tokens, $prevMeaningfulTokenIndex, $index)) { + continue; + } + + $firstOperand = $this->getConcatOperandType($tokens, $prevMeaningfulTokenIndex, -1); + + if (null === $firstOperand) { + continue; + } + + $this->fixConcatOperation($tokens, $firstOperand, $index, $secondOperand); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('juggle_simple_strings', 'Allow for simple string quote juggling if it results in more concat-operations merges.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @param _ConcatOperandType $firstOperand + * @param _ConcatOperandType $secondOperand + */ + private function fixConcatOperation(Tokens $tokens, array $firstOperand, int $concatIndex, array $secondOperand): void + { + // if both operands are of the same type then these operands can always be merged + + if ( + (self::STR_DOUBLE_QUOTE === $firstOperand['type'] && self::STR_DOUBLE_QUOTE === $secondOperand['type']) + || (self::STR_SINGLE_QUOTE === $firstOperand['type'] && self::STR_SINGLE_QUOTE === $secondOperand['type']) + ) { + $this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + if (self::STR_DOUBLE_QUOTE_VAR === $firstOperand['type'] && self::STR_DOUBLE_QUOTE_VAR === $secondOperand['type']) { + if ($this->operandsCanNotBeMerged($tokens, $firstOperand, $secondOperand)) { + return; + } + + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + // if any is double and the other is not, check for simple other, than merge with " + + $operands = [ + [$firstOperand, $secondOperand], + [$secondOperand, $firstOperand], + ]; + + foreach ($operands as $operandPair) { + [$operand1, $operand2] = $operandPair; + + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_DOUBLE_QUOTE === $operand2['type']) { + if ($this->operandsCanNotBeMerged($tokens, $operand1, $operand2)) { + return; + } + + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + + return; + } + + if (false === $this->configuration['juggle_simple_strings']) { + continue; + } + + if (self::STR_DOUBLE_QUOTE === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + + if ($this->isSimpleQuotedStringContent($operantContent)) { + $this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + + return; + } + + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + + if ($this->isSimpleQuotedStringContent($operantContent)) { + if ($this->operandsCanNotBeMerged($tokens, $operand1, $operand2)) { + return; + } + + $this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + + return; + } + } + } + + /** + * @param -1|1 $direction + * + * @return null|_ConcatOperandType + */ + private function getConcatOperandType(Tokens $tokens, int $index, int $direction): ?array + { + if ($tokens[$index]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $firstChar = $tokens[$index]->getContent(); + + if ('b' === $firstChar[0] || 'B' === $firstChar[0]) { + return null; // we don't care about these, priorities are set to do deal with these cases + } + + return [ + 'start' => $index, + 'end' => $index, + 'type' => '"' === $firstChar[0] ? self::STR_DOUBLE_QUOTE : self::STR_SINGLE_QUOTE, + ]; + } + + if ($tokens[$index]->equals('"')) { + $end = $tokens->getTokenOfKindSibling($index, $direction, ['"']); + + return [ + 'start' => 1 === $direction ? $index : $end, + 'end' => 1 === $direction ? $end : $index, + 'type' => self::STR_DOUBLE_QUOTE_VAR, + ]; + } + + return null; + } + + /** + * @param _ConcatOperandType $firstOperand + * @param _ConcatOperandType $secondOperand + */ + private function mergeConstantEscapedStringOperands( + Tokens $tokens, + array $firstOperand, + int $concatOperatorIndex, + array $secondOperand + ): void { + $quote = self::STR_DOUBLE_QUOTE === $firstOperand['type'] || self::STR_DOUBLE_QUOTE === $secondOperand['type'] ? '"' : "'"; + $firstOperandTokenContent = $tokens[$firstOperand['start']]->getContent(); + $secondOperandTokenContent = $tokens[$secondOperand['start']]->getContent(); + + $tokens[$firstOperand['start']] = new Token( + [ + \T_CONSTANT_ENCAPSED_STRING, + $quote.substr($firstOperandTokenContent, 1, -1).substr($secondOperandTokenContent, 1, -1).$quote, + ], + ); + + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($secondOperand['start']); + } + + /** + * @param _ConcatOperandType $firstOperand + * @param _ConcatOperandType $secondOperand + */ + private function mergeConstantEscapedStringVarOperands( + Tokens $tokens, + array $firstOperand, + int $concatOperatorIndex, + array $secondOperand + ): void { + // build up the new content + $newContent = ''; + + foreach ([$firstOperand, $secondOperand] as $operant) { + $operandContent = ''; + + for ($i = $operant['start']; $i <= $operant['end'];) { + $operandContent .= $tokens[$i]->getContent(); + $i = $tokens->getNextMeaningfulToken($i); + } + + $newContent .= substr($operandContent, 1, -1); + } + + // remove tokens making up the concat statement + + for ($i = $secondOperand['end']; $i >= $secondOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + + for ($i = $firstOperand['end']; $i > $firstOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + + // insert new tokens based on the new content + + $newTokens = Tokens::fromCode('overrideRange($firstOperand['start'], $firstOperand['start'], $insertTokens); + } + + private function clearConcatAndAround(Tokens $tokens, int $concatOperatorIndex): void + { + if ($tokens[$concatOperatorIndex + 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex + 1); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex); + + if ($tokens[$concatOperatorIndex - 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex - 1); + } + } + + private function isSimpleQuotedStringContent(string $candidate): bool + { + return !Preg::match('#[\$"\'\\\]#', substr($candidate, 1, -1)); + } + + private function containsLinebreak(Tokens $tokens, int $startIndex, int $endIndex): bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\R/', $tokens[$i]->getContent())) { + return true; + } + } + + return false; + } + + /** + * @param _ConcatOperandType $firstOperand + * @param _ConcatOperandType $secondOperand + */ + private function operandsCanNotBeMerged(Tokens $tokens, array $firstOperand, array $secondOperand): bool + { + // If the first operand does not end with a variable, no variables would be broken by concatenation. + if (self::STR_DOUBLE_QUOTE_VAR !== $firstOperand['type']) { + return false; + } + if (!$tokens[$firstOperand['end'] - 1]->isGivenKind(\T_VARIABLE)) { + return false; + } + + $allowedPatternsForSecondOperand = [ + '/^ .*/', // e.g. " foo", ' bar', " $baz" + '/^-(?!\>)/', // e.g. "-foo", '-bar', "-$baz" + ]; + + // If the first operand ends with a variable, the second operand should match one of the allowed patterns. + // Otherwise, the concatenation can break a variable in the first operand. + foreach ($allowedPatternsForSecondOperand as $allowedPattern) { + $secondOperandInnerContent = substr($tokens->generatePartialCode($secondOperand['start'], $secondOperand['end']), 1, -1); + + if (Preg::match($allowedPattern, $secondOperandInnerContent)) { + return false; + } + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php new file mode 100644 index 0000000..591cfe7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessNullsafeOperatorFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be useless Null-safe operator `?->` used.', + [ + new VersionSpecificCodeSample( + <<<'PHP' + parentMethod(); + } + } + + PHP, + new VersionSpecification(8_00_00), + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_00_00 && $tokens->isAllTokenKindsFound([\T_VARIABLE, \T_NULLSAFE_OBJECT_OPERATOR]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_NULLSAFE_OBJECT_OPERATOR)) { + continue; + } + + $nullsafeObjectOperatorIndex = $index; + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + continue; + } + + if ('$this' !== strtolower($tokens[$index]->getContent())) { + continue; + } + + $tokens[$nullsafeObjectOperatorIndex] = new Token([\T_OBJECT_OPERATOR, '->']); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php new file mode 100644 index 0000000..7c8c641 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Javier Spagnoletti + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NotOperatorWithSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Logical NOT operators (`!`) should have leading and trailing whitespaces.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('!')) { + if (!$tokens[$index + 1]->isWhitespace()) { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php new file mode 100644 index 0000000..6c23edd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Javier Spagnoletti + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NotOperatorWithSuccessorSpaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Logical NOT operators (`!`) should have one trailing whitespace.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound('!'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('!')) { + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php new file mode 100644 index 0000000..20e9249 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ObjectOperatorWithoutWhitespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be space before or after object operators `->` and `?->`.', + [new CodeSample(" b;\n")], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // [Structure] there should not be space before or after "->" or "?->" + foreach ($tokens as $index => $token) { + if (!$token->isObjectOperator()) { + continue; + } + + // clear whitespace before -> + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + + // clear whitespace after -> + if ($tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment()) { + $tokens->clearAt($index + 1); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php new file mode 100644 index 0000000..e8639e3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php @@ -0,0 +1,314 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * only_booleans?: bool, + * position?: 'beginning'|'end', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * only_booleans: bool, + * position: 'beginning'|'end', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class OperatorLinebreakFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const BOOLEAN_OPERATORS = [[\T_BOOLEAN_AND], [\T_BOOLEAN_OR], [\T_LOGICAL_AND], [\T_LOGICAL_OR], [\T_LOGICAL_XOR]]; + + private string $position = 'beginning'; + + /** + * @var list<_PhpTokenPrototypePartial> + */ + private array $operators = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Operators - when multiline - must always be at the beginning or at the end of the line.', + [ + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + 'end'], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->position = $this->configuration['position']; + $this->operators = self::BOOLEAN_OPERATORS; + + if (false === $this->configuration['only_booleans']) { + $this->operators = array_merge($this->operators, self::getNonBooleanOperators()); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('only_booleans', 'Whether to limit operators to only boolean ones.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('position', 'Whether to place operators at the beginning or at the end of the line.')) + ->setAllowedValues(['beginning', 'end']) + ->setDefault($this->position) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $referenceAnalyzer = new ReferenceAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + $index = $tokens->count(); + while ($index > 1) { + --$index; + + if (!$tokens[$index]->equalsAny($this->operators, false)) { + continue; + } + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) { + continue; + } + + if ($referenceAnalyzer->isReference($tokens, $index)) { + continue; + } + + if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + continue; + } + + if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) { + continue; + } + + $operatorIndices = [$index]; + if ($tokens[$index]->equals(':')) { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals('?')) { + $operatorIndices = [$prevIndex, $index]; + $index = $prevIndex; + } + } + + $this->fixOperatorLinebreak($tokens, $operatorIndices); + } + } + + /** + * @param non-empty-list $operatorIndices + */ + private function fixOperatorLinebreak(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices)); + $indexStart = $prevIndex + 1; + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices)); + $indexEnd = $nextIndex - 1; + + if (!$this->isMultiline($tokens, $indexStart, $indexEnd)) { + return; // operator is not surrounded by multiline whitespaces, do not touch it + } + + if ('beginning' === $this->position) { + if (!$this->isMultiline($tokens, max($operatorIndices), $indexEnd)) { + return; // operator already is placed correctly + } + $this->fixMoveToTheBeginning($tokens, $operatorIndices); + + return; + } + + if (!$this->isMultiline($tokens, $indexStart, min($operatorIndices))) { + return; // operator already is placed correctly + } + $this->fixMoveToTheEnd($tokens, $operatorIndices); + } + + /** + * @param non-empty-list $operatorIndices + */ + private function fixMoveToTheBeginning(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getNonEmptySibling(min($operatorIndices), -1); + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices)); + + for ($i = $nextIndex - 1; $i > max($operatorIndices); --$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) { + $isWhitespaceBefore = $tokens[$prevIndex]->isWhitespace(); + $inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, -1); + if ($isWhitespaceBefore) { + $inserts[] = new Token([\T_WHITESPACE, ' ']); + } + $tokens->insertAt($nextIndex, $inserts); + + break; + } + } + } + + /** + * @param non-empty-list $operatorIndices + */ + private function fixMoveToTheEnd(Tokens $tokens, array $operatorIndices): void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices)); + + /** @var int $nextIndex */ + $nextIndex = $tokens->getNonEmptySibling(max($operatorIndices), 1); + + for ($i = $prevIndex + 1; $i < max($operatorIndices); ++$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) { + $isWhitespaceAfter = $tokens[$nextIndex]->isWhitespace(); + $inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, 1); + if ($isWhitespaceAfter) { + array_unshift($inserts, new Token([\T_WHITESPACE, ' '])); + } + $tokens->insertAt($prevIndex + 1, $inserts); + + break; + } + } + } + + /** + * @param list $indices + * + * @return list + */ + private function getReplacementsAndClear(Tokens $tokens, array $indices, int $direction): array + { + return array_map( + static function (int $index) use ($tokens, $direction): Token { + $clone = $tokens[$index]; + + if ($tokens[$index + $direction]->isWhitespace()) { + $tokens->clearAt($index + $direction); + } + + $tokens->clearAt($index); + + return $clone; + }, + $indices, + ); + } + + private function isMultiline(Tokens $tokens, int $indexStart, int $indexEnd): bool + { + for ($index = $indexStart; $index <= $indexEnd; ++$index) { + if (str_contains($tokens[$index]->getContent(), "\n")) { + return true; + } + } + + return false; + } + + /** + * @return non-empty-list<_PhpTokenPrototypePartial> + */ + private static function getNonBooleanOperators(): array + { + return array_merge( + [ + '%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '^', '|', + [\T_AND_EQUAL], [\T_CONCAT_EQUAL], [\T_DIV_EQUAL], [\T_DOUBLE_ARROW], [\T_IS_EQUAL], [\T_IS_GREATER_OR_EQUAL], + [\T_IS_IDENTICAL], [\T_IS_NOT_EQUAL], [\T_IS_NOT_IDENTICAL], [\T_IS_SMALLER_OR_EQUAL], [\T_MINUS_EQUAL], + [\T_MOD_EQUAL], [\T_MUL_EQUAL], [\T_OR_EQUAL], [\T_PAAMAYIM_NEKUDOTAYIM], [\T_PLUS_EQUAL], [\T_POW], + [\T_POW_EQUAL], [\T_SL], [\T_SL_EQUAL], [\T_SR], [\T_SR_EQUAL], [\T_XOR_EQUAL], + [\T_COALESCE], [\T_SPACESHIP], [FCT::T_PIPE], + ], + array_map(static fn (int $id): array => [$id], Token::getObjectOperatorKinds()), + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php new file mode 100644 index 0000000..012036c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StandardizeIncrementFixer extends AbstractIncrementOperatorFixer +{ + private const EXPRESSION_END_TOKENS = [ + ';', + ')', + ']', + ',', + ':', + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [\T_CLOSE_TAG], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Increment and decrement operators should be used if possible.', + [ + new CodeSample("isAnyTokenKindsFound([\T_PLUS_EQUAL, \T_MINUS_EQUAL]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $expressionEnd = $tokens[$index]; + if (!$expressionEnd->equalsAny(self::EXPRESSION_END_TOKENS)) { + continue; + } + + $numberIndex = $tokens->getPrevMeaningfulToken($index); + $number = $tokens[$numberIndex]; + if (!$number->isGivenKind(\T_LNUMBER) || '1' !== $number->getContent()) { + continue; + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($numberIndex); + $operator = $tokens[$operatorIndex]; + if (!$operator->isGivenKind([\T_PLUS_EQUAL, \T_MINUS_EQUAL])) { + continue; + } + + $startIndex = $this->findStart($tokens, $operatorIndex); + + $this->clearRangeLeaveComments( + $tokens, + $tokens->getPrevMeaningfulToken($operatorIndex) + 1, + $numberIndex, + ); + + $tokens->insertAt( + $startIndex, + new Token($operator->isGivenKind(\T_PLUS_EQUAL) ? [\T_INC, '++'] : [\T_DEC, '--']), + ); + } + } + + /** + * Clear tokens in the given range unless they are comments. + */ + private function clearRangeLeaveComments(Tokens $tokens, int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $token = $tokens[$i]; + + if ($token->isComment()) { + continue; + } + + if ($token->isWhitespace("\n\r")) { + continue; + } + + $tokens->clearAt($i); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php new file mode 100644 index 0000000..311a531 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StandardizeNotEqualsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Replace all `<>` with `!=`.', + [new CodeSample(" \$c;\n")], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_IS_NOT_EQUAL); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_IS_NOT_EQUAL)) { + $tokens[$index] = new Token([\T_IS_NOT_EQUAL, '!=']); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php new file mode 100644 index 0000000..0e481e6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TernaryOperatorSpacesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Standardize spaces around ternary operator.', + [new CodeSample("isAllTokenKindsFound(['?', ':']); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $ternaryOperatorIndices = []; + + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['?', ':'])) { + continue; + } + + if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) { + continue; + } + + if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + continue; + } + + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) { + continue; + } + + $ternaryOperatorIndices[] = $index; + } + + foreach (array_reverse($ternaryOperatorIndices) as $index) { + $token = $tokens[$index]; + + if ($token->equals('?')) { + $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index); + + if ($tokens[$nextNonWhitespaceIndex]->equals(':')) { + // for `$a ?: $b` remove spaces between `?` and `:` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ''); + } else { + // for `$a ? $b : $c` ensure space after `?` + $this->ensureWhitespaceExistence($tokens, $index + 1, true); + } + + // for `$a ? $b : $c` ensure space before `?` + $this->ensureWhitespaceExistence($tokens, $index - 1, false); + + continue; + } + + if ($token->equals(':')) { + // for `$a ? $b : $c` ensure space after `:` + $this->ensureWhitespaceExistence($tokens, $index + 1, true); + + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + + if (!$prevNonWhitespaceToken->equals('?')) { + // for `$a ? $b : $c` ensure space before `:` + $this->ensureWhitespaceExistence($tokens, $index - 1, false); + } + } + } + } + + private function ensureWhitespaceExistence(Tokens $tokens, int $index, bool $after): void + { + if ($tokens[$index]->isWhitespace()) { + if ( + !str_contains($tokens[$index]->getContent(), "\n") + && !$tokens[$index - 1]->isComment() + ) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + + return; + } + + $index += $after ? 0 : 1; + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php new file mode 100644 index 0000000..cb08385 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php @@ -0,0 +1,223 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TernaryToElvisOperatorFixer extends AbstractFixer +{ + /** + * Lower precedence and other valid preceding tokens. + * + * Ordered by most common types first. + * + * @var non-empty-list<_PhpTokenPrototypePartial> + */ + private const VALID_BEFORE_ENDTYPES = [ + '=', + [\T_OPEN_TAG], + [\T_OPEN_TAG_WITH_ECHO], + '(', + ',', + ';', + '[', + '{', + '}', + [CT::T_ARRAY_INDEX_BRACE_OPEN], + [\T_AND_EQUAL], // &= + [\T_CONCAT_EQUAL], // .= + [\T_DIV_EQUAL], // /= + [\T_MINUS_EQUAL], // -= + [\T_MOD_EQUAL], // %= + [\T_MUL_EQUAL], // *= + [\T_OR_EQUAL], // |= + [\T_PLUS_EQUAL], // += + [\T_POW_EQUAL], // **= + [\T_SL_EQUAL], // <<= + [\T_SR_EQUAL], // >>= + [\T_XOR_EQUAL], // ^= + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use the Elvis operator `?:` where possible.', + [ + new CodeSample( + "isTokenKindFound('?'); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 5; $index > 1; --$index) { + if (!$tokens[$index]->equals('?')) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->equals(':')) { + continue; // Elvis is alive! + } + + // get and check what is before the `?` operator + + $beforeOperator = $this->getBeforeOperator($tokens, $index); + + if (null === $beforeOperator) { + continue; // contains something we cannot fix because of priorities + } + + // get what is after the `?` token + + $afterOperator = $this->getAfterOperator($tokens, $index); + + // if before and after the `?` operator are the same (in meaningful matter), clear after + + if (RangeAnalyzer::rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) { + $this->clearMeaningfulFromRange($tokens, $afterOperator); + } + } + } + + /** + * @return ?array{start: int, end: int} null if contains ++/-- operator + */ + private function getBeforeOperator(Tokens $tokens, int $index): ?array + { + $blockEdgeDefinitions = Tokens::getBlockEdgeDefinitions(); + $index = $tokens->getPrevMeaningfulToken($index); + $before = ['end' => $index]; + + while (!$tokens[$index]->equalsAny(self::VALID_BEFORE_ENDTYPES)) { + if ($tokens[$index]->isGivenKind([\T_INC, \T_DEC])) { + return null; + } + + $detectedBlockType = Tokens::detectBlockType($tokens[$index]); + + if (null === $detectedBlockType || $detectedBlockType['isStart']) { + $before['start'] = $index; + $index = $tokens->getPrevMeaningfulToken($index); + + continue; + } + + /** @phpstan-ignore-next-line offsetAccess.notFound (we just detected block type, we know it's definition exists under given PHP runtime) */ + $blockType = $blockEdgeDefinitions[$detectedBlockType['type']]; + $openCount = 1; + + do { + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind([\T_INC, \T_DEC])) { + return null; + } + + if ($tokens[$index]->equals($blockType['start'])) { + ++$openCount; + + continue; + } + + if ($tokens[$index]->equals($blockType['end'])) { + --$openCount; + } + } while (1 >= $openCount); + + $before['start'] = $index; + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!isset($before['start'])) { + return null; + } + + return $before; + } + + /** + * @return array{start: int, end: int} + */ + private function getAfterOperator(Tokens $tokens, int $index): array + { + $index = $tokens->getNextMeaningfulToken($index); + $after = ['start' => $index]; + + do { + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null !== $blockType) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + } + + $after['end'] = $index; + $index = $tokens->getNextMeaningfulToken($index); + } while (!$tokens[$index]->equals(':')); + + return $after; + } + + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range): void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php new file mode 100644 index 0000000..8487435 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php @@ -0,0 +1,222 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TernaryToNullCoalescingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Use `null` coalescing operator `??` where possible.', + [ + new CodeSample( + "isTokenKindFound(\T_ISSET); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $issetIndices = array_keys($tokens->findGivenKind(\T_ISSET)); + + foreach (array_reverse($issetIndices) as $issetIndex) { + $this->fixIsset($tokens, $issetIndex); + } + } + + /** + * @param int $index of `T_ISSET` token + */ + private function fixIsset(Tokens $tokens, int $index): void + { + $prevTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if ($this->isHigherPrecedenceAssociativityOperator($tokens[$prevTokenIndex])) { + return; + } + + $startBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startBraceIndex); + + $ternaryQuestionMarkIndex = $tokens->getNextMeaningfulToken($endBraceIndex); + + if (!$tokens[$ternaryQuestionMarkIndex]->equals('?')) { + return; // we are not in a ternary operator + } + + // search what is inside the isset() + $issetTokens = $this->getMeaningfulSequence($tokens, $startBraceIndex, $endBraceIndex); + + if ($this->hasChangingContent($issetTokens)) { + return; // some weird stuff inside the isset + } + + $issetCode = $issetTokens->generateCode(); + + if ('$this' === $issetCode) { + return; // null coalescing operator does not with $this + } + + // search what is inside the middle argument of ternary operator + $ternaryColonIndex = $tokens->getNextTokenOfKind($ternaryQuestionMarkIndex, [':']); + $ternaryFirstOperandTokens = $this->getMeaningfulSequence($tokens, $ternaryQuestionMarkIndex, $ternaryColonIndex); + + if ($issetCode !== $ternaryFirstOperandTokens->generateCode()) { + return; // regardless of non-meaningful tokens, the operands are different + } + + $ternaryFirstOperandIndex = $tokens->getNextMeaningfulToken($ternaryQuestionMarkIndex); + + // preserve comments and spaces + $comments = []; + $commentStarted = false; + + for ($loopIndex = $index; $loopIndex < $ternaryFirstOperandIndex; ++$loopIndex) { + if ($tokens[$loopIndex]->isComment()) { + $comments[] = $tokens[$loopIndex]; + $commentStarted = true; + } elseif ($commentStarted) { + if ($tokens[$loopIndex]->isWhitespace()) { + $comments[] = $tokens[$loopIndex]; + } + + $commentStarted = false; + } + } + + $tokens[$ternaryColonIndex] = new Token([\T_COALESCE, '??']); + $tokens->overrideRange($index, $ternaryFirstOperandIndex - 1, $comments); + } + + /** + * Get the sequence of meaningful tokens and returns a new Tokens instance. + * + * @param int $start start index + * @param int $end end index + */ + private function getMeaningfulSequence(Tokens $tokens, int $start, int $end): Tokens + { + $sequence = []; + $index = $start; + + while ($index < $end) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($index >= $end || null === $index) { + break; + } + + $sequence[] = $tokens[$index]; + } + + return Tokens::fromArray($sequence); + } + + /** + * Check if the requested token is an operator computed + * before the ternary operator along with the `isset()`. + */ + private function isHigherPrecedenceAssociativityOperator(Token $token): bool + { + return + $token->isGivenKind([ + \T_ARRAY_CAST, + \T_BOOLEAN_AND, + \T_BOOLEAN_OR, + \T_BOOL_CAST, + \T_COALESCE, + \T_DEC, + \T_DOUBLE_CAST, + \T_INC, + \T_INT_CAST, + \T_IS_EQUAL, + \T_IS_GREATER_OR_EQUAL, + \T_IS_IDENTICAL, + \T_IS_NOT_EQUAL, + \T_IS_NOT_IDENTICAL, + \T_IS_SMALLER_OR_EQUAL, + \T_OBJECT_CAST, + \T_POW, + \T_SL, + \T_SPACESHIP, + \T_SR, + \T_STRING_CAST, + \T_UNSET_CAST, + ]) + || $token->equalsAny([ + '!', + '%', + '&', + '*', + '+', + '-', + '/', + ':', + '^', + '|', + '~', + '.', + ]); + } + + /** + * Check if the `isset()` content may change if called multiple times. + * + * @param Tokens $tokens The original token list + */ + private function hasChangingContent(Tokens $tokens): bool + { + foreach ($tokens as $token) { + if ($token->isGivenKind([ + \T_DEC, + \T_INC, + \T_YIELD, + \T_YIELD_FROM, + ]) || $token->equals('(')) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php new file mode 100644 index 0000000..f297166 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * only_dec_inc?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * only_dec_inc: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class UnaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Unary operators should be placed adjacent to their operands.', + [ + new CodeSample(" false], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NotOperatorWithSpaceFixer, NotOperatorWithSuccessorSpaceFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('only_dec_inc', 'Limit to increment and decrement operators.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (true === $this->configuration['only_dec_inc'] && !$tokens[$index]->isGivenKind([\T_DEC, \T_INC])) { + continue; + } + + if ($tokensAnalyzer->isUnarySuccessorOperator($index)) { + if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + + continue; + } + + if ($tokensAnalyzer->isUnaryPredecessorOperator($index)) { + $tokens->removeTrailingWhitespace($index); + + continue; + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php new file mode 100644 index 0000000..29b4be8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlankLineAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line.', + [new CodeSample("isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + $newlineFound = false; + foreach ($tokens as $token) { + if (($token->isWhitespace() || $token->isGivenKind(\T_OPEN_TAG)) && str_contains($token->getContent(), "\n")) { + $newlineFound = true; + + break; + } + } + + // ignore one-line files + if (!$newlineFound) { + return; + } + + $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0; + $token = $tokens[$openTagIndex]; + + if (!str_contains($token->getContent(), "\n")) { + $tokens[$openTagIndex] = new Token([$token->getId(), rtrim($token->getContent()).$lineEnding]); + } + + $newLineIndex = $openTagIndex + 1; + if (!$tokens->offsetExists($newLineIndex)) { + return; + } + + if ($tokens[$newLineIndex]->isWhitespace()) { + if (!str_contains($tokens[$newLineIndex]->getContent(), "\n")) { + $tokens[$newLineIndex] = new Token([\T_WHITESPACE, $lineEnding.$tokens[$newLineIndex]->getContent()]); + } + } else { + $tokens->insertAt($newLineIndex, new Token([\T_WHITESPACE, $lineEnding])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php new file mode 100644 index 0000000..ce7843b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php @@ -0,0 +1,267 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * format?: 'long'|'short', + * long_function?: 'echo'|'print', + * shorten_simple_statements_only?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * format: 'long'|'short', + * long_function: 'echo'|'print', + * shorten_simple_statements_only: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Michele Locati + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EchoTagSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @internal */ + public const OPTION_FORMAT = 'format'; + + /** @internal */ + public const OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY = 'shorten_simple_statements_only'; + + /** @internal */ + public const OPTION_LONG_FUNCTION = 'long_function'; + + /** @internal */ + public const FORMAT_SHORT = 'short'; + + /** @internal */ + public const FORMAT_LONG = 'long'; + + /** @internal */ + public const LONG_FUNCTION_ECHO = 'echo'; + + /** @internal */ + public const LONG_FUNCTION_PRINT = 'print'; + + private const SUPPORTED_FORMAT_OPTIONS = [ + self::FORMAT_LONG, + self::FORMAT_SHORT, + ]; + + private const SUPPORTED_LONGFUNCTION_OPTIONS = [ + self::LONG_FUNCTION_ECHO, + self::LONG_FUNCTION_PRINT, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + $sample = <<<'EOT' + + + + + + EOT; + + return new FixerDefinition( + 'Replaces short-echo ` self::FORMAT_LONG]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG, self::OPTION_LONG_FUNCTION => self::LONG_FUNCTION_PRINT]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT]), + new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT, self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY => false]), + ], + null, + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoMixedEchoPrintFixer. + * Must run after NoUselessPrintfFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) { + return $tokens->isAnyTokenKindsFound([\T_ECHO, \T_PRINT]); + } + + return $tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder(self::OPTION_FORMAT, 'The desired language construct.')) + ->setAllowedValues(self::SUPPORTED_FORMAT_OPTIONS) + ->setDefault(self::FORMAT_LONG) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_LONG_FUNCTION, 'The function to be used to expand the short echo tags.')) + ->setAllowedValues(self::SUPPORTED_LONGFUNCTION_OPTIONS) + ->setDefault(self::LONG_FUNCTION_ECHO) + ->getOption(), + (new FixerOptionBuilder(self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY, 'Render short-echo tags only in case of simple code.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) { + $this->longToShort($tokens); + } else { + $this->shortToLong($tokens); + } + } + + private function longToShort(Tokens $tokens): void + { + $count = $tokens->count(); + + for ($index = 0; $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_OPEN_TAG)) { + continue; + } + + $echoPrintIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $echoPrintIndex) { + return; + } + + if (!$tokens[$echoPrintIndex]->isGivenKind([\T_ECHO, \T_PRINT])) { + $index = $echoPrintIndex; + + continue; + } + + if (true === $this->configuration[self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY] && $this->isComplexCode($tokens, $echoPrintIndex + 1)) { + $index = $echoPrintIndex; + + continue; + } + + $tokens[$index] = new Token([\T_OPEN_TAG_WITH_ECHO, 'ensureWhitespaceAtIndex($index + 1, 0, ''); + + $this->fixWhitespaceBeforeEchoPrint($tokens, $echoPrintIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($echoPrintIndex); + } + } + + private function shortToLong(Tokens $tokens): void + { + if (self::LONG_FUNCTION_PRINT === $this->configuration[self::OPTION_LONG_FUNCTION]) { + $echoToken = [\T_PRINT, 'print']; + } else { + $echoToken = [\T_ECHO, 'echo']; + } + + $index = -1; + + while (true) { + $index = $tokens->getNextTokenOfKind($index, [[\T_OPEN_TAG_WITH_ECHO]]); + + if (null === $index) { + return; + } + + $replace = [new Token([\T_OPEN_TAG, 'isWhitespace()) { + $replace[] = new Token([\T_WHITESPACE, ' ']); + } + + $tokens->overrideRange($index, $index, $replace); + ++$index; + } + } + + /** + * Check if $tokens, starting at $index, contains "complex code", that is, the content + * of the echo tag contains more than a simple "echo something". + * + * This is done by a very quick test: if the tag contains non-whitespace tokens after + * a semicolon, we consider it as "complex". + * + * @example `` is false (not complex) + * @example `` is false (not "complex") + * @example `` is true ("complex") + */ + private function isComplexCode(Tokens $tokens, int $index): bool + { + $semicolonFound = false; + + for ($count = $tokens->count(); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_CLOSE_TAG)) { + return false; + } + + if (';' === $token->getContent()) { + $semicolonFound = true; + } elseif ($semicolonFound && !$token->isWhitespace()) { + return true; + } + } + + return false; + } + + private function fixWhitespaceBeforeEchoPrint(Tokens $tokens, int $echoPrintIndex): void + { + $whitespaceBeforeEchoPrintIndex = $tokens->getNonEmptySibling($echoPrintIndex, -1); + + if (!$tokens[$whitespaceBeforeEchoPrintIndex]->isWhitespace()) { + return; + } + + $prevWhitespaceBeforeEchoPrintIndex = $tokens->getNonEmptySibling($whitespaceBeforeEchoPrintIndex, -1); + if ( + $tokens[$prevWhitespaceBeforeEchoPrintIndex]->isGivenKind(\T_COMMENT) + && !Preg::match('/\*\/$/', $tokens[$prevWhitespaceBeforeEchoPrintIndex]->getContent()) + ) { + return; + } + + $tokens->clearAt($whitespaceBeforeEchoPrintIndex); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php new file mode 100644 index 0000000..46da9b8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php @@ -0,0 +1,135 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR1 ¶2.1. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FullOpeningTagFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHP code must use the long `generateCode(); + + // replace all echo ' echo ' $token) { + if ($token->isGivenKind(\T_OPEN_TAG)) { + $tokenContent = $token->getContent(); + $possibleOpenContent = substr($content, $tokensOldContentLength, 5); + + if (false === $possibleOpenContent || 'isGivenKind([\T_COMMENT, \T_DOC_COMMENT, \T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_STRING])) { + $tokenContent = ''; + $tokenContentLength = 0; + $parts = explode('getContent()); + $iLast = \count($parts) - 1; + + foreach ($parts as $i => $part) { + $tokenContent .= $part; + $tokenContentLength += \strlen($part); + + if ($i !== $iLast) { + $originalTokenContent = substr($content, $tokensOldContentLength + $tokenContentLength, 5); + if ('getId(), $tokenContent]); + $token = $newTokens[$index]; + } + + $tokensOldContentLength += \strlen($token->getContent()); + } + + $tokens->overrideRange(0, $tokens->count() - 1, $newTokens); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php new file mode 100644 index 0000000..b30c6a3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Ceeram + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LinebreakAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure there is no code on the same line as the PHP open tag.', + [new CodeSample("isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0; + + // ignore if linebreak already present + if (str_contains($tokens[$openTagIndex]->getContent(), "\n")) { + return; + } + + $newlineFound = false; + foreach ($tokens as $token) { + if (($token->isWhitespace() || $token->isGivenKind(\T_OPEN_TAG)) && str_contains($token->getContent(), "\n")) { + $newlineFound = true; + + break; + } + } + + // ignore one-line files + if (!$newlineFound) { + return; + } + + $tokens[$openTagIndex] = new Token([\T_OPEN_TAG, rtrim($tokens[$openTagIndex]->getContent()).$this->whitespacesConfig->getLineEnding()]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php new file mode 100644 index 0000000..510568d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoClosingTagFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The closing `?>` tag MUST be omitted from files containing only PHP.', + [new CodeSample("\n")], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \count($tokens) >= 2 && $tokens->isMonolithicPhp() && $tokens->isTokenKindFound(\T_CLOSE_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $closeTags = $tokens->findGivenKind(\T_CLOSE_TAG); + $index = array_key_first($closeTags); + + if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isWhitespace()) { + $tokens->clearAt($index - 1); + } + $tokens->clearAt($index); + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny([';', '}', [\T_OPEN_TAG]])) { + $tokens->insertAt($prevIndex + 1, new Token(';')); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAssertNewNamesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAssertNewNamesFixer.php new file mode 100644 index 0000000..4ed16c3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAssertNewNamesFixer.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Krzysztof Ciszewski + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitAssertNewNamesFixer extends AbstractPhpUnitFixer +{ + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Rename deprecated PHPUnit assertions like `assertFileNotExists` to new methods like `assertFileDoesNotExist`.', + [ + new CodeSample( + <<<'PHP' + assertFileNotExists("test.php"); + $this->assertNotIsWritable("path.php"); + } + } + + PHP, + ), + ], + null, + 'Fixer could be risky if one is overriding PHPUnit\'s native methods.', + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return -10; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) { + $this->fixAssertNewNames($tokens, $assertCall); + } + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertNewNames(Tokens $tokens, array $assertCall): void + { + $replacements = [ + 'assertnotisreadable' => 'assertIsNotReadable', + 'assertnotiswritable' => 'assertIsNotWritable', + 'assertdirectorynotexists' => 'assertDirectoryDoesNotExist', + 'assertfilenotexists' => 'assertFileDoesNotExist', + 'assertdirectorynotisreadable' => 'assertDirectoryIsNotReadable', + 'assertdirectorynotiswritable' => 'assertDirectoryIsNotWriteable', + 'assertfilenotisreadable' => 'assertFileIsNotReadable', + 'assertfilenotiswritable' => 'assertFileIsNotWriteable', + 'assertregexp' => 'assertMatchesRegularExpression', + 'assertnotregexp' => 'assertDoesNotMatchRegularExpression', + ]; + $replacement = $replacements[$assertCall['loweredName']] ?? null; + + if (null === $replacement) { + return; + } + + $tokens[$assertCall['index']] = new Token([ + \T_STRING, + $replacement, + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAttributesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAttributesFixer.php new file mode 100644 index 0000000..35eda13 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitAttributesFixer.php @@ -0,0 +1,651 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Processor\ImportProcessor; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * keep_annotations?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * keep_annotations: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitAttributesFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @var array */ + private array $fixingMap; + + public function __construct() + { + parent::__construct(); + $this->prepareFixingMap(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'PHP' + true]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \PHP_VERSION_ID >= 8_00_00 && parent::isCandidate($tokens); + } + + /** + * {@inheritdoc} + * + * Must run before FullyQualifiedStrictTypesFixer, NoEmptyPhpdocFixer, PhpdocSeparationFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer. + * Must run after PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer. + */ + public function getPriority(): int + { + return 8; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('keep_annotations', 'Whether to keep annotations or not. This may be helpful for projects that support PHP before version 8 or PHPUnit before version 10.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + $docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex); + if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + $startIndex = $docBlockIndex; + } + + for ($index = $endIndex; $index >= $startIndex; --$index) { + if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $targetIndex = $tokens->getTokenNotOfKindSibling( + $index, + 1, + [[\T_ABSTRACT], [\T_COMMENT], [\T_FINAL], [\T_FUNCTION], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_STATIC], [\T_WHITESPACE]], + ); + $annotationScope = $tokens[$targetIndex]->isGivenKind(\T_CLASS) ? 'class' : 'method'; + + $docBlock = new DocBlock($tokens[$index]->getContent()); + + $presentAttributes = []; + foreach (array_reverse($docBlock->getAnnotations()) as $annotation) { + $annotationName = $annotation->getTag()->getName(); + + if (!isset($this->fixingMap[$annotationName])) { + continue; + } + if (!self::shouldBeFixed($annotationName, $annotationScope)) { + continue; + } + + /** @phpstan-ignore-next-line */ + $tokensToInsert = self::{$this->fixingMap[$annotationName]}($tokens, $index, $annotation); + + $presentAttributes[$annotationName] ??= self::isAttributeAlreadyPresent($tokens, $index, $tokensToInsert); + + if ([] === $tokensToInsert) { + continue; + } + + if (!$presentAttributes[$annotationName]) { + $tokens->insertSlices([$index + 1 => $tokensToInsert]); + } + + if (!$this->configuration['keep_annotations']) { + $annotation->remove(); + } + } + + if ('' === $docBlock->getContent()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens[$index] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]); + } + } + } + + private function prepareFixingMap(): void + { + // annotations that map to attribute without parameters + foreach ([ + 'after', + 'afterClass', + 'before', + 'beforeClass', + 'coversNothing', + 'doesNotPerformAssertions', + 'large', + 'medium', + 'runInSeparateProcess', + 'runTestsInSeparateProcesses', + 'small', + 'test', + 'preCondition', + 'postCondition', + ] as $annotation) { + $this->fixingMap[$annotation] = 'fixWithoutParameters'; + } + + // annotations that map to attribute with single string value + foreach (['group', 'testDox', 'ticket'] as $annotation) { + $this->fixingMap[$annotation] = 'fixWithSingleStringValue'; + } + + // annotations that map from 'enabled'/'disabled' value to attribute with boolean value + foreach (['backupGlobals', 'backupStaticAttributes', 'preserveGlobalState'] as $annotation) { + $this->fixingMap[$annotation] = 'fixWithEnabledDisabledValue'; + } + + // annotations that has custom mapping function + $this->fixingMap['covers'] = 'fixCovers'; + $this->fixingMap['dataProvider'] = 'fixDataProvider'; + $this->fixingMap['depends'] = 'fixDepends'; + $this->fixingMap['requires'] = 'fixRequires'; + $this->fixingMap['testWith'] = 'fixTestWith'; + $this->fixingMap['uses'] = 'fixUses'; + } + + private static function shouldBeFixed(string $annotationName, string $annotationScope): bool + { + if ( + 'method' === $annotationScope + && \in_array($annotationName, ['covers', 'large', 'medium', 'runTestsInSeparateProcesses', 'small', 'uses'], true) + ) { + return false; + } + + if ( + 'class' === $annotationScope + && \in_array($annotationName, ['after', 'afterClass', 'before', 'beforeClass', 'dataProvider', 'depends', 'postCondition', 'preCondition', 'runInSeparateProcess', 'test', 'testWith'], true) + ) { + return false; + } + + return true; + } + + /** + * @param list $tokensToInsert + */ + private static function isAttributeAlreadyPresent( + Tokens $tokens, + int $index, + array $tokensToInsert + ): bool { + $attributeIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$attributeIndex]->isGivenKind(\T_ATTRIBUTE)) { + return false; + } + + $insertedClassName = ''; + foreach (\array_slice($tokensToInsert, 3) as $token) { + if ($token->equals('(') || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + break; + } + $insertedClassName .= $token->getContent(); + } + + foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) { + foreach ($attributeAnalysis->getAttributes() as $attribute) { + $className = ltrim(AttributeAnalyzer::determineAttributeFullyQualifiedName($tokens, $attribute['name'], $attribute['start']), '\\'); + + if ($insertedClassName === $className) { + return true; + } + + if ('PHPUnit\Framework\Attributes\TestWithJson' === $insertedClassName && 'PHPUnit\Framework\Attributes\TestWith' === $className) { + return true; + } + } + } + + return false; + } + + /** + * @return non-empty-list + */ + private static function fixWithoutParameters(Tokens $tokens, int $index, Annotation $annotation): array + { + return self::createAttributeTokens($tokens, $index, self::getAttributeNameForAnnotation($annotation)); + } + + /** + * @return list + */ + private static function fixWithSingleStringValue(Tokens $tokens, int $index, Annotation $annotation): array + { + Preg::match( + \sprintf('/@%s\s+(.*\S)(?:\R|\s*\*+\/$)/', $annotation->getTag()->getName()), + $annotation->getContent(), + $matches, + ); + if (!isset($matches[1])) { + return []; + } + + return self::createAttributeTokens( + $tokens, + $index, + self::getAttributeNameForAnnotation($annotation), + self::createEscapedStringToken($matches[1]), + ); + } + + /** + * @return list + */ + private static function fixWithEnabledDisabledValue(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + if (!isset($matches[1])) { + return []; + } + + return self::createAttributeTokens( + $tokens, + $index, + self::getAttributeNameForAnnotation($annotation), + new Token([\T_STRING, isset($matches[1]) && 'enabled' === $matches[1] ? 'true' : 'false']), + ); + } + + /** + * @return list + */ + private static function fixCovers(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + \assert(isset($matches[1])); + + $splitByDoubleColon = explode('::', $matches[1]); + $splitByDoubleColonCount = \count($splitByDoubleColon); + \assert(isset($splitByDoubleColon[0])); + + if (1 === $splitByDoubleColonCount) { + // naive guessing if it's a Trait or Class, as we do not have access to codebase to make sure, but it's better than nothing + $isTrait = str_ends_with($splitByDoubleColon[0], 'Trait'); + + return self::createAttributeTokens( + $tokens, + $index, + $isTrait ? 'CoversTrait' : 'CoversClass', + ...self::toClassConstant($splitByDoubleColon[0]), + ); + } + + if (2 === $splitByDoubleColonCount) { + \assert(isset($splitByDoubleColon[1])); + if ('' === $splitByDoubleColon[0]) { + return self::createAttributeTokens( + $tokens, + $index, + 'CoversFunction', + self::createEscapedStringToken($splitByDoubleColon[1]), + ); + } + + if ('' !== $splitByDoubleColon[1]) { + return self::createAttributeTokens( + $tokens, + $index, + 'CoversMethod', + ...self::toClassConstant($splitByDoubleColon[0]), + ...[ + new Token(','), + new Token([\T_WHITESPACE, ' ']), + self::fixNameAndCreateEscapedStringToken($splitByDoubleColon[1]), + ], + ); + } + } + + // unexpected format, do not attempt to fix + return []; + } + + /** + * @return list + */ + private static function fixDataProvider(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + if (!isset($matches[1])) { + return []; + } + + if (str_contains($matches[1], '::')) { + // @phpstan-ignore offsetAccess.notFound + [$class, $method] = explode('::', $matches[1]); + + return self::createAttributeTokens( + $tokens, + $index, + 'DataProviderExternal', + ...[ + ...self::toClassConstant($class), + new Token(','), + new Token([\T_WHITESPACE, ' ']), + self::fixNameAndCreateEscapedStringToken($method), + ], + ); + } + + return self::createAttributeTokens($tokens, $index, 'DataProvider', self::fixNameAndCreateEscapedStringToken($matches[1])); + } + + /** + * @see https://github.com/sebastianbergmann/phpunit/blob/11.5.12/src/Metadata/Parser/AnnotationParser.php#L266 + */ + private static function fixNameAndCreateEscapedStringToken(string $methodName): Token + { + return self::createEscapedStringToken(rtrim($methodName, " ()\n\r\t\v\x00")); + } + + /** + * @return list + */ + private static function fixDepends(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + if (!isset($matches[1])) { + return []; + } + + $nameSuffix = ''; + $depended = $matches[1]; + if (isset($matches[2])) { + if ('clone' === $matches[1]) { + $nameSuffix = 'UsingDeepClone'; + $depended = $matches[2]; + } elseif ('shallowClone' === $matches[1]) { + $nameSuffix = 'UsingShallowClone'; + $depended = $matches[2]; + } + } + + $class = null; + $method = $depended; + if (str_contains($depended, '::')) { + // @phpstan-ignore offsetAccess.notFound + [$class, $method] = explode('::', $depended); + + if ('class' === $method) { + $method = null; + $nameSuffix = '' === $nameSuffix ? 'OnClass' : ('OnClass'.$nameSuffix); + } else { + $nameSuffix = ('External'.$nameSuffix); + } + } + + $attributeTokens = []; + if (null !== $class) { + $attributeTokens = self::toClassConstant($class); + } + if (null !== $method) { + if ([] !== $attributeTokens) { + $attributeTokens[] = new Token(','); + $attributeTokens[] = new Token([\T_WHITESPACE, ' ']); + } + $attributeTokens[] = self::createEscapedStringToken($method); + } + + return self::createAttributeTokens($tokens, $index, 'Depends'.$nameSuffix, ...$attributeTokens); + } + + /** + * @return list + */ + private static function fixRequires(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + if (!isset($matches[1])) { + return []; + } + + $map = [ + 'extension' => 'RequiresPhpExtension', + 'function' => 'RequiresFunction', + 'PHP' => 'RequiresPhp', + 'PHPUnit' => 'RequiresPhpunit', + 'OS' => 'RequiresOperatingSystem', + 'OSFAMILY' => 'RequiresOperatingSystemFamily', + 'setting' => 'RequiresSetting', + ]; + + if (!isset($matches[2]) || !isset($map[$matches[1]])) { + return []; + } + + $attributeName = $map[$matches[1]]; + + if ('RequiresFunction' === $attributeName && str_contains($matches[2], '::')) { + // @phpstan-ignore offsetAccess.notFound + [$class, $method] = explode('::', $matches[2]); + + $attributeName = 'RequiresMethod'; + $attributeTokens = [ + ...self::toClassConstant($class), + new Token(','), + new Token([\T_WHITESPACE, ' ']), + self::createEscapedStringToken($method), + ]; + } elseif (\in_array($attributeName, ['RequiresPhp', 'RequiresPhpunit'], true) && isset($matches[3])) { + $attributeTokens = [self::createEscapedStringToken($matches[2].' '.$matches[3])]; + } else { + $attributeTokens = [self::createEscapedStringToken(self::fixVersionConstraint($matches[2]))]; + } + + if (isset($matches[3]) && !\in_array($attributeName, ['RequiresPhp', 'RequiresPhpunit'], true)) { + $attributeTokens[] = new Token(','); + $attributeTokens[] = new Token([\T_WHITESPACE, ' ']); + $attributeTokens[] = self::createEscapedStringToken(self::fixVersionConstraint($matches[3])); + } + + return self::createAttributeTokens($tokens, $index, $attributeName, ...$attributeTokens); + } + + private static function fixVersionConstraint(string $version): string + { + if (Preg::match('/^[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?$/', $version)) { + $version = '>= '.$version; + } + + return $version; + } + + /** + * @return list + */ + private static function fixTestWith(Tokens $tokens, int $index, Annotation $annotation): array + { + $content = $annotation->getContent(); + $content = Preg::replace('/@testWith\s+/', '', $content); + $content = Preg::replace('/(^|\R)\s+\**\s*/', "\n", $content); + $content = trim($content); + if ('' === $content) { + return []; + } + + $attributeTokens = []; + foreach (explode("\n", $content) as $json) { + $attributeTokens = array_merge( + $attributeTokens, + self::createAttributeTokens($tokens, $index, 'TestWithJson', self::createEscapedStringToken($json)), + ); + } + + return $attributeTokens; + } + + /** + * @return list + */ + private static function fixUses(Tokens $tokens, int $index, Annotation $annotation): array + { + $matches = self::getMatches($annotation); + if (!isset($matches[1])) { + return []; + } + + if (str_starts_with($matches[1], '::')) { + $attributeName = 'UsesFunction'; + $attributeTokens = [self::createEscapedStringToken(substr($matches[1], 2))]; + } elseif (Preg::match('/^[a-zA-Z\d\\\]+$/', $matches[1])) { + $attributeName = 'UsesClass'; + $attributeTokens = self::toClassConstant($matches[1]); + } else { + return []; + } + + return self::createAttributeTokens($tokens, $index, $attributeName, ...$attributeTokens); + } + + /** + * @return list + */ + private static function getMatches(Annotation $annotation): array + { + Preg::match( + \sprintf('/@%s\s+(\S+)(?:\s+(\S+))?(?:\s+(.+\S))?\s*(?:\R|\*+\/$)/', $annotation->getTag()->getName()), + $annotation->getContent(), + $matches, + ); + + \assert(array_is_list($matches)); // preg_match matches is not well typed, it depends on used regex, let's assure the type to instruct SCA + + return $matches; + } + + private static function getAttributeNameForAnnotation(Annotation $annotation): string + { + $annotationName = $annotation->getTag()->getName(); + + return 'backupStaticAttributes' === $annotationName + ? 'BackupStaticProperties' + : ucfirst($annotationName); + } + + /** + * @return non-empty-list + */ + private static function createAttributeTokens( + Tokens $tokens, + int $index, + string $className, + Token ...$attributeTokens + ): array { + if ([] !== $attributeTokens) { + $attributeTokens = [ + new Token('('), + ...$attributeTokens, + new Token(')'), + ]; + } + + return [ + clone $tokens[$index + 1], + new Token([\T_ATTRIBUTE, '#[']), + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, 'PHPUnit']), + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, 'Framework']), + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, 'Attributes']), + new Token([\T_NS_SEPARATOR, '\\']), + new Token([\T_STRING, $className]), + ...$attributeTokens, + new Token([CT::T_ATTRIBUTE_CLOSE, ']']), + ]; + } + + /** + * @param non-empty-string $name + * + * @return list + */ + private static function toClassConstant(string $name): array + { + return [ + ...ImportProcessor::tokenizeName($name), + new Token([\T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ]; + } + + private static function createEscapedStringToken(string $value): Token + { + return new Token([\T_CONSTANT_ENCAPSED_STRING, "'".str_replace("'", "\\'", $value)."'"]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php new file mode 100644 index 0000000..bf49e15 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php @@ -0,0 +1,214 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * assertions?: list<'assertEquals'|'assertNotEquals'|'assertNotSame'|'assertSame'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * assertions: list<'assertEquals'|'assertNotEquals'|'assertNotSame'|'assertSame'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitConstructFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertion method calls like `->assertSame(true, $foo)` should be written with dedicated method like `->assertTrue($foo)`.', + [ + new CodeSample( + <<<'PHP' + assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } + } + + PHP, + ['assertions' => ['assertSame', 'assertNotSame']], + ), + ], + null, + 'Fixer could be risky if one is overriding PHPUnit\'s native methods.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return -8; + } + + /** + * @uses fixAssertNegative() + * @uses fixAssertPositive() + */ + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + // no assertions to be fixed - fast return + if ([] === $this->configuration['assertions']) { + return; + } + + foreach ($this->configuration['assertions'] as $assertionMethod) { + for ($index = $startIndex; $index < $endIndex; ++$index) { + $index = \call_user_func_array( + \in_array($assertionMethod, ['assertSame', 'assertEquals'], true) + ? [$this, 'fixAssertPositive'] + : [$this, 'fixAssertNegative'], + [$tokens, $index, $assertionMethod], + ); + + if (null === $index) { + break; + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $assertMethods = [ + 'assertEquals', + 'assertNotEquals', + 'assertNotSame', + 'assertSame', + ]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($assertMethods)]) + ->setDefault($assertMethods) + ->getOption(), + ]); + } + + private function fixAssertNegative(Tokens $tokens, int $index, string $method): ?int + { + return $this->fixAssert([ + 'false' => 'assertNotFalse', + 'null' => 'assertNotNull', + 'true' => 'assertNotTrue', + ], $tokens, $index, $method); + } + + private function fixAssertPositive(Tokens $tokens, int $index, string $method): ?int + { + return $this->fixAssert([ + 'false' => 'assertFalse', + 'null' => 'assertNull', + 'true' => 'assertTrue', + ], $tokens, $index, $method); + } + + /** + * @param array $map + */ + private function fixAssert(array $map, Tokens $tokens, int $index, string $method): ?int + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + $sequence = $tokens->findSequence( + [ + [\T_STRING, $method], + '(', + ], + $index, + ); + + if (null === $sequence) { + return null; + } + + $sequenceIndices = array_keys($sequence); + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $sequenceIndices[0])) { + return null; + } + + \assert(isset($sequenceIndices[1])); + $sequenceIndices[2] = $tokens->getNextMeaningfulToken($sequenceIndices[1]); + $firstParameterToken = $tokens[$sequenceIndices[2]]; + + if (!$firstParameterToken->isNativeConstant()) { + return $sequenceIndices[2]; + } + + $sequenceIndices[3] = $tokens->getNextMeaningfulToken($sequenceIndices[2]); + + // return if first method argument is an expression, not value + if (!$tokens[$sequenceIndices[3]]->equals(',')) { + return $sequenceIndices[3]; + } + + \assert(isset($sequenceIndices[0], $map[strtolower($firstParameterToken->getContent())])); + $tokens[$sequenceIndices[0]] = new Token([\T_STRING, $map[strtolower($firstParameterToken->getContent())]]); + $tokens->clearRange($sequenceIndices[2], $tokens->getNextNonWhitespace($sequenceIndices[3]) - 1); + + return $sequenceIndices[3]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderMethodOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderMethodOrderFixer.php new file mode 100644 index 0000000..aaab51e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderMethodOrderFixer.php @@ -0,0 +1,294 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ClassNotation\OrderedClassElementsFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * placement?: 'after'|'before', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * placement: 'after'|'before', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _ClassElement from OrderedClassElementsFixer + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDataProviderMethodOrderFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Data provider method must be placed after/before the last/first test where used.', + [ + new CodeSample( + <<<'PHP' + 'before', + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer. + * Must run after OrderedClassElementsFixer. + */ + public function getPriority(): int + { + return 64; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('placement', 'Where to place the data provider relative to the test where used.')) + ->setAllowedValues(['after', 'before']) + ->setDefault('after') + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $elements = $this->getElements($tokens, $startIndex); + + if (0 === \count($elements)) { + return; + } + + $endIndex = $elements[array_key_last($elements)]['end']; + + $dataProvidersWithUsagePairs = $this->getDataProvidersWithUsagePairs($tokens, $startIndex, $endIndex); + $origUsageDataProviderOrderPairs = $this->getOrigUsageDataProviderOrderPairs($dataProvidersWithUsagePairs); + + $sorted = $elements; + $providersPlaced = []; + if ('before' === $this->configuration['placement']) { + foreach ($origUsageDataProviderOrderPairs as [$usageName, $providerName]) { + if (!isset($providersPlaced[$providerName])) { + $providersPlaced[$providerName] = true; + + $sorted = $this->moveMethodElement($sorted, $usageName, $providerName, false); + } + } + } else { + $sameUsageName = false; + $sameProviderName = false; + foreach ($origUsageDataProviderOrderPairs as [$usageName, $providerName]) { + if (!isset($providersPlaced[$providerName])) { + $providersPlaced[$providerName] = true; + + $sortedBefore = $sorted; + $sorted = $this->moveMethodElement( + $sorted, + $usageName === $sameUsageName // @phpstan-ignore argument.type (https://github.com/phpstan/phpstan/issues/12482) + ? $sameProviderName + : $usageName, + $providerName, + true, + ); + + // honour multiple providers order for one test + $sameUsageName = $usageName; + $sameProviderName = $providerName; + + // keep placement after the first test + if ($sortedBefore !== $sorted) { + unset($providersPlaced[$providerName]); + } + } + } + } + + if ($sorted !== $elements) { + $this->sortTokens($tokens, $startIndex, $endIndex, $sorted); + } + } + + /** + * @return list<_ClassElement> + */ + private function getElements(Tokens $tokens, int $startIndex): array + { + $methodOrderFixer = new OrderedClassElementsFixer(); + + return \Closure::bind(static fn () => $methodOrderFixer->getElements($tokens, $startIndex), null, OrderedClassElementsFixer::class)(); + } + + /** + * @param list<_ClassElement> $elements + */ + private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements): void + { + $methodOrderFixer = new OrderedClassElementsFixer(); + + \Closure::bind(static fn () => $methodOrderFixer->sortTokens($tokens, $startIndex, $endIndex, $elements), null, OrderedClassElementsFixer::class)(); + } + + /** + * @param list<_ClassElement> $elements + * + * @return list<_ClassElement> + */ + private function moveMethodElement(array $elements, string $nameKeep, string $nameToMove, bool $after): array + { + $i = 0; + $iKeep = false; + $iToMove = false; + foreach ($elements as $element) { + if ('method' === $element['type']) { + if ($element['name'] === $nameKeep) { + $iKeep = $i; + } elseif ($element['name'] === $nameToMove) { + $iToMove = $i; + } + } + + ++$i; + } + \assert(false !== $iKeep); + \assert(false !== $iToMove); + + if ($iToMove === $iKeep + ($after ? 1 : -1)) { + return $elements; + } + + $elementToMove = $elements[$iToMove]; // @phpstan-ignore offsetAccess.notFound + unset($elements[$iToMove]); + + $c = $iKeep + + ($after ? 1 : 0) + + ($iToMove < $iKeep ? -1 : 0); + + return [ + ...\array_slice($elements, 0, $c), + $elementToMove, + ...\array_slice($elements, $c), + ]; + } + + /** + * @return list + * }> + */ + private function getDataProvidersWithUsagePairs(Tokens $tokens, int $startIndex, int $endIndex): array + { + $dataProvidersWithUsagePairs = []; + + $dataProviderAnalyzer = new DataProviderAnalyzer(); + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderAnalysis) { + $usages = []; + foreach ($dataProviderAnalysis->getUsageIndices() as $usageIndex) { + $methodNameTokens = $tokens->findSequence([[\T_FUNCTION], [\T_STRING]], $usageIndex[0], $endIndex); + if (null === $methodNameTokens) { + continue; + } + + $usages[array_key_last($methodNameTokens)] = [ + array_key_last($methodNameTokens), + end($methodNameTokens)->getContent(), + $usageIndex[1], + ]; + } + \assert([] !== $usages); + + $dataProvidersWithUsagePairs[] = [ + [$dataProviderAnalysis->getNameIndex(), $dataProviderAnalysis->getName()], + $usages, + ]; + } + + return $dataProvidersWithUsagePairs; + } + + /** + * @param list + * }> $dataProvidersWithUsagePairs + * + * @return list + */ + private function getOrigUsageDataProviderOrderPairs(array $dataProvidersWithUsagePairs): array + { + $origUsagesOrderPairs = []; + foreach ($dataProvidersWithUsagePairs as [$dataProviderPair, $usagePairs]) { + foreach ($usagePairs as $usagePair) { + $origUsagesOrderPairs[] = [$usagePair, $dataProviderPair[1]]; + } + } + uasort($origUsagesOrderPairs, static function (array $a, array $b): int { + $cmp = $a[0][0] <=> $b[0][0]; + + return 0 !== $cmp + ? $cmp + : $a[0][2] <=> $b[0][2]; + }); + + $origUsageDataProviderOrderPairs = []; + foreach (array_map(static fn (array $v): array => [$v[0][1], $v[1]], $origUsagesOrderPairs) as [$usageName, $providerName]) { + $origUsageDataProviderOrderPairs[] = [$usageName, $providerName]; + } + + return $origUsageDataProviderOrderPairs; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php new file mode 100644 index 0000000..4bab4ac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php @@ -0,0 +1,215 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * prefix?: string, + * suffix?: string, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * prefix: string, + * suffix: string, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDataProviderNameFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Data provider names must match the name of the test.', + [ + new CodeSample( + <<<'PHP' + 'data_', + 'suffix' => '', + ], + ), + new CodeSample( + <<<'PHP' + 'provides', + 'suffix' => 'Data', + ], + ), + ], + null, + 'Fixer could be risky if one is calling data provider by name as function.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('prefix', 'Prefix that replaces "test".')) + ->setAllowedTypes(['string']) + ->setDefault('provide') + ->getOption(), + (new FixerOptionBuilder('suffix', 'Suffix to be present at the end.')) + ->setAllowedTypes(['string']) + ->setDefault('Cases') + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $dataProviders = (new DataProviderAnalyzer())->getDataProviders($tokens, $startIndex, $endIndex); + + $methodsProviders = []; + $providersMethods = []; + foreach ($dataProviders as $dataProviderAnalysis) { + foreach ($dataProviderAnalysis->getUsageIndices() as [$usageIndex]) { + $methodIndex = $tokens->getNextTokenOfKind($usageIndex, [[\T_FUNCTION]]); + $methodsProviders[$methodIndex][$dataProviderAnalysis->getName()] = $usageIndex; + $providersMethods[$dataProviderAnalysis->getName()][$methodIndex] = $usageIndex; + } + } + + foreach ($dataProviders as $dataProviderAnalysis) { + // @phpstan-ignore offsetAccess.notFound + if (\count($providersMethods[$dataProviderAnalysis->getName()]) > 1) { + continue; + } + + $methodIndex = $tokens->getNextTokenOfKind($dataProviderAnalysis->getUsageIndices()[0][0], [[\T_FUNCTION]]); + // @phpstan-ignore offsetAccess.notFound + if (\count($methodsProviders[$methodIndex]) > 1) { + continue; + } + + $dataProviderNewName = $this->getDataProviderNameForUsageIndex($tokens, $methodIndex); + if (null !== $tokens->findSequence([[\T_FUNCTION], [\T_STRING, $dataProviderNewName]], $startIndex, $endIndex)) { + continue; + } + + foreach ($dataProviderAnalysis->getUsageIndices() as [$usageIndex]) { + $tokens[$dataProviderAnalysis->getNameIndex()] = new Token([\T_STRING, $dataProviderNewName]); + + $newContent = $tokens[$usageIndex]->isGivenKind(\T_DOC_COMMENT) + ? Preg::replace( + \sprintf('/(@dataProvider\s+)%s/', $dataProviderAnalysis->getName()), + \sprintf('$1%s', $dataProviderNewName), + $tokens[$usageIndex]->getContent(), + ) + : \sprintf('%1$s%2$s%1$s', $tokens[$usageIndex]->getContent()[0], $dataProviderNewName); + + $tokens[$usageIndex] = new Token([$tokens[$usageIndex]->getId(), $newContent]); + } + } + } + + private function getDataProviderNameForUsageIndex(Tokens $tokens, int $index): string + { + do { + if ($tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + $index = $tokens->getNextMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind(\T_STRING)); + + $name = $tokens[$index]->getContent(); + + $name = Preg::replace('/^test_*/i', '', $name); + + if ('' === $this->configuration['prefix']) { + $name = lcfirst($name); + } elseif ('_' !== substr($this->configuration['prefix'], -1)) { + $name = ucfirst($name); + } + + return $this->configuration['prefix'].$name.$this->configuration['suffix']; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php new file mode 100644 index 0000000..28f0bbf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php @@ -0,0 +1,126 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDataProviderReturnTypeFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The return type of PHPUnit data provider must be `iterable`.', + [ + new CodeSample( + <<<'PHP' + getDataProviders($tokens, $startIndex, $endIndex)) as $dataProviderAnalysis) { + $typeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $dataProviderAnalysis->getNameIndex()); + + if (null === $typeAnalysis) { + $argumentsStart = $tokens->getNextTokenOfKind($dataProviderAnalysis->getNameIndex(), ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $argumentsStart); + + $tokens->insertAt( + $argumentsEnd + 1, + [ + new Token([CT::T_TYPE_COLON, ':']), + new Token([\T_WHITESPACE, ' ']), + new Token([\T_STRING, 'iterable']), + ], + ); + + continue; + } + + if ('iterable' === $typeAnalysis->getName()) { + continue; + } + + $typeStartIndex = $tokens->getNextMeaningfulToken($typeAnalysis->getStartIndex() - 1); + $typeEndIndex = $typeAnalysis->getEndIndex(); + + // @TODO: drop condition and it's body when PHP 8+ is required + if ($tokens->generatePartialCode($typeStartIndex, $typeEndIndex) !== $typeAnalysis->getName()) { + continue; + } + + $tokens->overrideRange($typeStartIndex, $typeEndIndex, [new Token([\T_STRING, 'iterable'])]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php new file mode 100644 index 0000000..feae559 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * force?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * force: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDataProviderStaticFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Data providers must be static.', + [ + new CodeSample( + <<<'PHP' + getData1(); } + public function provideSomethingCases2() { self::getData2(); } + } + + PHP, + ['force' => true], + ), + new CodeSample( + <<<'PHP' + getData1(); } + public function provideSomething2Cases() { self::getData2(); } + } + + PHP, + ['force' => false], + ), + ], + null, + 'Fixer could be risky if one is calling data provider function dynamically.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'force', + 'Whether to make the data providers static even if they have a dynamic class call' + .' (may introduce fatal error "using $this when not in object context",' + .' and you may have to adjust the code manually by converting dynamic calls to static ones).', + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $dataProviderAnalyzer = new DataProviderAnalyzer(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $inserts = []; + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderDefinitionIndex) { + $methodStartIndex = $tokens->getNextTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), ['{']); + if (null !== $methodStartIndex) { + $methodEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $methodStartIndex); + + if (false === $this->configuration['force'] && null !== $tokens->findSequence([[\T_VARIABLE, '$this']], $methodStartIndex, $methodEndIndex)) { + continue; + } + } + + /** @var int $functionIndex */ + $functionIndex = $tokens->getPrevTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), [[\T_FUNCTION]]); + + $methodAttributes = $tokensAnalyzer->getMethodAttributes($functionIndex); + if (false !== $methodAttributes['static']) { + continue; + } + + $inserts[$functionIndex] = [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])]; + } + $tokens->insertSlices($inserts); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php new file mode 100644 index 0000000..9f90921 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php @@ -0,0 +1,606 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '3.0'|'3.5'|'5.0'|'5.6'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '3.0'|'3.5'|'5.0'|'5.6'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDedicateAssertFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private const FIX_MAP = [ + 'array_key_exists' => [ + 'positive' => 'assertArrayHasKey', + 'negative' => 'assertArrayNotHasKey', + 'argument_count' => 2, + ], + 'empty' => [ + 'positive' => 'assertEmpty', + 'negative' => 'assertNotEmpty', + ], + 'file_exists' => [ + 'positive' => 'assertFileExists', + 'negative' => 'assertFileNotExists', + ], + 'is_array' => true, + 'is_bool' => true, + 'is_callable' => true, + 'is_dir' => [ + 'positive' => 'assertDirectoryExists', + 'negative' => 'assertDirectoryNotExists', + ], + 'is_double' => true, + 'is_float' => true, + 'is_infinite' => [ + 'positive' => 'assertInfinite', + 'negative' => 'assertFinite', + ], + 'is_int' => true, + 'is_integer' => true, + 'is_long' => true, + 'is_nan' => [ + 'positive' => 'assertNan', + 'negative' => false, + ], + 'is_null' => [ + 'positive' => 'assertNull', + 'negative' => 'assertNotNull', + ], + 'is_numeric' => true, + 'is_object' => true, + 'is_readable' => [ + 'positive' => 'assertIsReadable', + 'negative' => 'assertNotIsReadable', + ], + 'is_real' => true, + 'is_resource' => true, + 'is_scalar' => true, + 'is_string' => true, + 'is_writable' => [ + 'positive' => 'assertIsWritable', + 'negative' => 'assertNotIsWritable', + ], + 'str_contains' => [ // since 7.5 + 'positive' => 'assertStringContainsString', + 'negative' => 'assertStringNotContainsString', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + 'str_ends_with' => [ // since 3.4 + 'positive' => 'assertStringEndsWith', + 'negative' => 'assertStringEndsNotWith', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + 'str_starts_with' => [ // since 3.4 + 'positive' => 'assertStringStartsWith', + 'negative' => 'assertStringStartsNotWith', + 'argument_count' => 2, + 'swap_arguments' => true, + ], + ]; + + /** + * @var list + */ + private array $functions = []; + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertions like `assertInternalType`, `assertFileExists`, should be used over `assertTrue`.', + [ + new CodeSample( + <<<'PHP' + assertTrue(is_float( $a), "my message"); + $this->assertTrue(is_nan($a)); + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + assertTrue(is_dir($a)); + $this->assertTrue(is_writable($a)); + $this->assertTrue(is_readable($a)); + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_5_6], + ), + ], + null, + 'Fixer could be risky if one is overriding PHPUnit\'s native methods.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, PhpUnitAssertNewNamesFixer, PhpUnitDedicateAssertInternalTypeFixer. + * Must run after ModernizeStrposFixer, NoAliasFunctionsFixer, PhpUnitConstructFixer. + */ + public function getPriority(): int + { + return -9; + } + + protected function configurePostNormalisation(): void + { + // assertions added in 3.0: assertArrayNotHasKey assertArrayHasKey assertFileNotExists assertFileExists assertNotNull, assertNull + $this->functions = [ + 'array_key_exists', + 'file_exists', + 'is_null', + 'str_ends_with', + 'str_starts_with', + ]; + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_3_5)) { + // assertions added in 3.5: assertInternalType assertNotEmpty assertEmpty + $this->functions = array_merge($this->functions, [ + 'empty', + 'is_array', + 'is_bool', + 'is_boolean', + 'is_callable', + 'is_double', + 'is_float', + 'is_int', + 'is_integer', + 'is_long', + 'is_numeric', + 'is_object', + 'is_real', + 'is_scalar', + 'is_string', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_0)) { + // assertions added in 5.0: assertFinite assertInfinite assertNan + $this->functions = array_merge($this->functions, [ + 'is_infinite', + 'is_nan', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { + // assertions added in 5.6: assertDirectoryExists assertDirectoryNotExists assertIsReadable assertNotIsReadable assertIsWritable assertNotIsWritable + $this->functions = array_merge($this->functions, [ + 'is_dir', + 'is_readable', + 'is_writable', + ]); + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_7_5)) { + $this->functions = array_merge($this->functions, [ + 'str_contains', + ]); + } + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) { + // test and fix for assertTrue/False to dedicated asserts + if (\in_array($assertCall['loweredName'], ['asserttrue', 'assertfalse'], true)) { + $this->fixAssertTrueFalse($tokens, $argumentsAnalyzer, $assertCall); + + continue; + } + + if (\in_array( + $assertCall['loweredName'], + ['assertsame', 'assertnotsame', 'assertequals', 'assertnotequals'], + true, + )) { + $this->fixAssertSameEquals($tokens, $assertCall); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([ + PhpUnitTargetVersion::VERSION_3_0, + PhpUnitTargetVersion::VERSION_3_5, + PhpUnitTargetVersion::VERSION_5_0, + PhpUnitTargetVersion::VERSION_5_6, + PhpUnitTargetVersion::VERSION_NEWEST, + ]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalse(Tokens $tokens, ArgumentsAnalyzer $argumentsAnalyzer, array $assertCall): void + { + $testDefaultNamespaceTokenIndex = null; + $testIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + + if (!$tokens[$testIndex]->isGivenKind([\T_EMPTY, \T_STRING])) { + if ($this->fixAssertTrueFalseInstanceof($tokens, $assertCall, $testIndex)) { + return; + } + + if (!$tokens[$testIndex]->isGivenKind(\T_NS_SEPARATOR)) { + return; + } + + $testDefaultNamespaceTokenIndex = $testIndex; + $testIndex = $tokens->getNextMeaningfulToken($testIndex); + } + + $testOpenIndex = $tokens->getNextMeaningfulToken($testIndex); + + if (!$tokens[$testOpenIndex]->equals('(')) { + return; + } + + $testCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $testOpenIndex); + $assertCallCloseIndex = $tokens->getNextMeaningfulToken($testCloseIndex); + + if (!$tokens[$assertCallCloseIndex]->equalsAny([')', ','])) { + return; + } + + $content = strtolower($tokens[$testIndex]->getContent()); + + if (!\in_array($content, $this->functions, true)) { + return; + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $testOpenIndex, $testCloseIndex); + $isPositive = 'asserttrue' === $assertCall['loweredName']; + + if (isset(self::FIX_MAP[$content]) && \is_array(self::FIX_MAP[$content])) { + $fixDetails = self::FIX_MAP[$content]; + $expectedCount = $fixDetails['argument_count'] ?? 1; + + if ($expectedCount !== \count($arguments)) { + return; + } + + $isPositive = $isPositive ? 'positive' : 'negative'; + + if (false === $fixDetails[$isPositive]) { + return; + } + + $tokens[$assertCall['index']] = new Token([\T_STRING, $fixDetails[$isPositive]]); + $this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex); + + if ($fixDetails['swap_arguments'] ?? false) { + if (2 !== $expectedCount) { + throw new \RuntimeException('Can only swap two arguments, please update map or logic.'); + } + + $this->swapArguments($tokens, $arguments); + } + + return; + } + + if (1 !== \count($arguments)) { + return; + } + + $type = substr($content, 3); + + $tokens[$assertCall['index']] = new Token([\T_STRING, $isPositive ? 'assertInternalType' : 'assertNotInternalType']); + $tokens[$testIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "'".$type."'"]); + $tokens[$testOpenIndex] = new Token(','); + + $tokens->clearTokenAndMergeSurroundingWhitespace($testCloseIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($testCloseIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + if (!$tokens[$testOpenIndex + 1]->isWhitespace()) { + $tokens->insertAt($testOpenIndex + 1, new Token([\T_WHITESPACE, ' '])); + } + + if (null !== $testDefaultNamespaceTokenIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex); + } + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalseInstanceof(Tokens $tokens, array $assertCall, int $testIndex): bool + { + $isPositiveAssertion = 'asserttrue' === $assertCall['loweredName']; + + if ($tokens[$testIndex]->equals('!')) { + $variableIndex = $tokens->getNextMeaningfulToken($testIndex); + $isPositiveCondition = false; + } else { + $variableIndex = $testIndex; + $isPositiveCondition = true; + } + + if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) { + return false; + } + + $instanceOfIndex = $tokens->getNextMeaningfulToken($variableIndex); + + if (!$tokens[$instanceOfIndex]->isGivenKind(\T_INSTANCEOF)) { + return false; + } + + $classEndIndex = $tokens->getNextMeaningfulToken($instanceOfIndex); + $classPartTokens = []; + + do { + $classPartTokens[] = $tokens[$classEndIndex]; + $classEndIndex = $tokens->getNextMeaningfulToken($classEndIndex); + } while ($tokens[$classEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR, \T_VARIABLE])); + + if ($tokens[$classEndIndex]->equalsAny([',', ')'])) { // do the fixing + $isInstanceOfVar = $classPartTokens[0]->isGivenKind(\T_VARIABLE); + $insertIndex = $testIndex - 1; + $newTokens = []; + + foreach ($classPartTokens as $token) { + $newTokens[++$insertIndex] = clone $token; + } + + if (!$isInstanceOfVar) { + $newTokens[++$insertIndex] = new Token([\T_DOUBLE_COLON, '::']); + $newTokens[++$insertIndex] = new Token([CT::T_CLASS_CONSTANT, 'class']); + } + + $newTokens[++$insertIndex] = new Token(','); + $newTokens[++$insertIndex] = new Token([\T_WHITESPACE, ' ']); + $newTokens[++$insertIndex] = clone $tokens[$variableIndex]; + + for ($i = $classEndIndex - 1; $i >= $testIndex; --$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + + $name = $isPositiveAssertion && $isPositiveCondition || !$isPositiveAssertion && !$isPositiveCondition + ? 'assertInstanceOf' + : 'assertNotInstanceOf'; + + $tokens->insertSlices($newTokens); + $tokens[$assertCall['index']] = new Token([\T_STRING, $name]); + } + + return true; + } + + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertSameEquals(Tokens $tokens, array $assertCall): void + { + // @ $this->/self::assertEquals/Same([$nextIndex]) + $expectedIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + + // do not fix + // let $a = [1,2]; $b = "2"; + // "$this->assertEquals("2", count($a)); $this->assertEquals($b, count($a)); $this->assertEquals(2.1, count($a));" + + if ($tokens[$expectedIndex]->isGivenKind(\T_VARIABLE)) { + if (!$tokens[$tokens->getNextMeaningfulToken($expectedIndex)]->equals(',')) { + return; + } + } elseif (!$tokens[$expectedIndex]->isGivenKind([\T_LNUMBER, \T_VARIABLE])) { + return; + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex]) + $commaIndex = $tokens->getNextMeaningfulToken($expectedIndex); + + if (!$tokens[$commaIndex]->equals(',')) { + return; + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,$countCallIndex]) + $countCallIndex = $tokens->getNextMeaningfulToken($commaIndex); + + if ($tokens[$countCallIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $defaultNamespaceTokenIndex = $countCallIndex; + $countCallIndex = $tokens->getNextMeaningfulToken($countCallIndex); + } else { + $defaultNamespaceTokenIndex = null; + } + + if (!$tokens[$countCallIndex]->isGivenKind(\T_STRING)) { + return; + } + + $lowerContent = strtolower($tokens[$countCallIndex]->getContent()); + + if (!\in_array($lowerContent, ['count', 'sizeof'], true)) { + return; // not a call to "count" or "sizeOf" + } + + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,[$defaultNamespaceTokenIndex,]$countCallIndex,$countCallOpenBraceIndex]) + $countCallOpenBraceIndex = $tokens->getNextMeaningfulToken($countCallIndex); + + if (!$tokens[$countCallOpenBraceIndex]->equals('(')) { + return; + } + + $countCallCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $countCallOpenBraceIndex); + $afterCountCallCloseBraceIndex = $tokens->getNextMeaningfulToken($countCallCloseBraceIndex); + + if (!$tokens[$afterCountCallCloseBraceIndex]->equalsAny([')', ','])) { + return; + } + + $this->removeFunctionCall( + $tokens, + $defaultNamespaceTokenIndex, + $countCallIndex, + $countCallOpenBraceIndex, + $countCallCloseBraceIndex, + ); + + $tokens[$assertCall['index']] = new Token([ + \T_STRING, + false === strpos($assertCall['loweredName'], 'not', 6) ? 'assertCount' : 'assertNotCount', + ]); + } + + private function removeFunctionCall(Tokens $tokens, ?int $callNSIndex, int $callIndex, int $openIndex, int $closeIndex): void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); + + if (null !== $callNSIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); + + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + } + + /** + * @param array $argumentsIndices + */ + private function swapArguments(Tokens $tokens, array $argumentsIndices): void + { + \assert(isset(array_keys($argumentsIndices)[0], array_keys($argumentsIndices)[1])); + [$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices); + + \assert(isset($argumentsIndices[$firstArgumentIndex], $argumentsIndices[$secondArgumentIndex])); + $firstArgumentEndIndex = $argumentsIndices[$firstArgumentIndex]; + $secondArgumentEndIndex = $argumentsIndices[$secondArgumentIndex]; + + $firstClone = $this->cloneAndClearTokens($tokens, $firstArgumentIndex, $firstArgumentEndIndex); + $secondClone = $this->cloneAndClearTokens($tokens, $secondArgumentIndex, $secondArgumentEndIndex); + + \assert([] !== $firstClone); + \assert([] !== $secondClone); + + if (!$firstClone[0]->isWhitespace()) { + array_unshift($firstClone, new Token([\T_WHITESPACE, ' '])); + } + + $tokens->insertAt($secondArgumentIndex, $firstClone); + + if ($secondClone[0]->isWhitespace()) { + array_shift($secondClone); + } + + $tokens->insertAt($firstArgumentIndex, $secondClone); + } + + /** + * @return list + */ + private function cloneAndClearTokens(Tokens $tokens, int $start, int $end): array + { + $clone = []; + + for ($i = $start; $i <= $end; ++$i) { + if ('' === $tokens[$i]->getContent()) { + continue; + } + + $clone[] = clone $tokens[$i]; + $tokens->clearAt($i); + } + + return $clone; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php new file mode 100644 index 0000000..ba1cbad --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php @@ -0,0 +1,210 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '7.5'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '7.5'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitDedicateAssertInternalTypeFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private array $typeToDedicatedAssertMap = [ + 'array' => 'assertIsArray', + 'boolean' => 'assertIsBool', + 'bool' => 'assertIsBool', + 'double' => 'assertIsFloat', + 'float' => 'assertIsFloat', + 'integer' => 'assertIsInt', + 'int' => 'assertIsInt', + 'null' => 'assertNull', + 'numeric' => 'assertIsNumeric', + 'object' => 'assertIsObject', + 'real' => 'assertIsFloat', + 'resource' => 'assertIsResource', + 'string' => 'assertIsString', + 'scalar' => 'assertIsScalar', + 'callable' => 'assertIsCallable', + 'iterable' => 'assertIsIterable', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit assertions like `assertIsArray` should be used over `assertInternalType`.', + [ + new CodeSample( + <<<'PHP' + assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_7_5], + ), + ], + null, + 'Risky when PHPUnit methods are overridden or when project has PHPUnit incompatibilities.', + ); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority(): int + { + return -16; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_7_5, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $anonymousClassIndices = []; + $tokenAnalyzer = new TokensAnalyzer($tokens); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$tokenAnalyzer->isAnonymousClass($index)) { + continue; + } + + $openingBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $openingBraceIndex); + + $anonymousClassIndices[$closingBraceIndex] = $openingBraceIndex; + } + + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (isset($anonymousClassIndices[$index])) { + $index = $anonymousClassIndices[$index]; + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + + $functionName = strtolower($tokens[$index]->getContent()); + + if ('assertinternaltype' !== $functionName && 'assertnotinternaltype' !== $functionName) { + continue; + } + + $bracketTokenIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$bracketTokenIndex]->equals('(')) { + continue; + } + + $expectedTypeTokenIndex = $tokens->getNextMeaningfulToken($bracketTokenIndex); + $expectedTypeToken = $tokens[$expectedTypeTokenIndex]; + + if (!$expectedTypeToken->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + $expectedType = trim($expectedTypeToken->getContent(), '\'"'); + + if (!isset($this->typeToDedicatedAssertMap[$expectedType])) { + continue; + } + + $commaTokenIndex = $tokens->getNextMeaningfulToken($expectedTypeTokenIndex); + + if (!$tokens[$commaTokenIndex]->equals(',')) { + continue; + } + + $newAssertion = $this->typeToDedicatedAssertMap[$expectedType]; + + if ('assertnotinternaltype' === $functionName) { + $newAssertion = str_replace('Is', 'IsNot', $newAssertion); + $newAssertion = str_replace('Null', 'NotNull', $newAssertion); + } + + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($commaTokenIndex); + + $tokens->overrideRange($index, $nextMeaningfulTokenIndex - 1, [ + new Token([\T_STRING, $newAssertion]), + new Token('('), + ]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php new file mode 100644 index 0000000..704ed9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php @@ -0,0 +1,302 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '5.2'|'5.6'|'8.4'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '5.2'|'5.6'|'8.4'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitExpectationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private array $methodMap = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.', + [ + new CodeSample( + <<<'PHP' + setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_8_4], + ), + new CodeSample( + <<<'PHP' + setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_5_6], + ), + new CodeSample( + <<<'PHP' + setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_5_2], + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitNoExpectationAnnotationFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->methodMap = [ + 'setExpectedException' => 'expectExceptionMessage', + ]; + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp'; + } + + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_8_4)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageMatches'; + $this->methodMap['expectExceptionMessageRegExp'] = 'expectExceptionMessageMatches'; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_2, PhpUnitTargetVersion::VERSION_5_6, PhpUnitTargetVersion::VERSION_8_4, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + foreach (Token::getObjectOperatorKinds() as $objectOperator) { + $this->applyPhpUnitClassFixWithObjectOperator($tokens, $startIndex, $endIndex, $objectOperator); + } + } + + private function applyPhpUnitClassFixWithObjectOperator(Tokens $tokens, int $startIndex, int $endIndex, int $objectOperator): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + $oldMethodSequence = [ + [\T_VARIABLE, '$this'], + [$objectOperator], + [\T_STRING], + ]; + + for ($index = $startIndex; $startIndex < $endIndex; ++$index) { + /** @var null|array{Token, Token, Token} $match */ + $match = $tokens->findSequence($oldMethodSequence, $index); + + if (null === $match) { + return; + } + + [$thisIndex, , $index] = array_keys($match); + + if (!isset($this->methodMap[$tokens[$index]->getContent()])) { + continue; + } + $newExpectedExceptionName = $this->methodMap[$tokens[$index]->getContent()]; + + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + $argumentsCnt = \count($arguments); + + $argumentsReplacements = ['expectException', $newExpectedExceptionName, 'expectExceptionCode']; + + $indent = $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $thisIndex); + + $isMultilineWhitespace = false; + + for ($cnt = $argumentsCnt - 1; $cnt >= 1; --$cnt) { + \assert(isset(array_keys($arguments)[$cnt])); + $argStart = array_keys($arguments)[$cnt]; + $argBefore = $tokens->getPrevMeaningfulToken($argStart); + + if (!isset($argumentsReplacements[$cnt])) { + throw new \LogicException(\sprintf('Unexpected index %d to find replacement method.', $cnt)); + } + + if ('expectExceptionMessage' === $argumentsReplacements[$cnt]) { + $paramIndicatorIndex = $tokens->getNextMeaningfulToken($argBefore); + $afterParamIndicatorIndex = $tokens->getNextMeaningfulToken($paramIndicatorIndex); + + if ( + $tokens[$paramIndicatorIndex]->equals([\T_STRING, 'null'], false) + && $tokens[$afterParamIndicatorIndex]->equals(')') + ) { + if ($tokens[$argBefore + 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore + 1); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($argBefore); + $tokens->clearTokenAndMergeSurroundingWhitespace($paramIndicatorIndex); + + continue; + } + } + + $isMultilineWhitespace = $isMultilineWhitespace || ($tokens[$argStart]->isWhitespace() && !$tokens[$argStart]->isWhitespace(" \t")); + $tokensOverrideArgStart = [ + new Token([\T_WHITESPACE, $indent]), + new Token([\T_VARIABLE, '$this']), + new Token([\T_OBJECT_OPERATOR, '->']), + new Token([\T_STRING, $argumentsReplacements[$cnt]]), + new Token('('), + ]; + $tokensOverrideArgBefore = [ + new Token(')'), + new Token(';'), + ]; + + if ($isMultilineWhitespace) { + $tokensOverrideArgStart[] = new Token([\T_WHITESPACE, $indent.$this->whitespacesConfig->getIndent()]); + array_unshift($tokensOverrideArgBefore, new Token([\T_WHITESPACE, $indent])); + } + + if ($tokens[$argStart]->isWhitespace()) { + $tokens->overrideRange($argStart, $argStart, $tokensOverrideArgStart); + } else { + $tokens->insertAt($argStart, $tokensOverrideArgStart); + } + + $tokens->overrideRange($argBefore, $argBefore, $tokensOverrideArgBefore); + } + + $methodName = 'expectException'; + if ('expectExceptionMessageRegExp' === $tokens[$index]->getContent()) { + $methodName = $newExpectedExceptionName; + } + $tokens[$index] = new Token([\T_STRING, $methodName]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php new file mode 100644 index 0000000..aa5dc7d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Roland Franssen + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit annotations should be a FQCNs including a root namespace.', + [ + new CodeSample( + <<<'PHP' + getPrevTokenOfKind($startIndex, [[\T_DOC_COMMENT]]); + + if (null !== $prevDocCommentIndex) { + $startIndex = $prevDocCommentIndex; + } + + $this->fixPhpUnitClass($tokens, $startIndex, $endIndex); + } + + private function fixPhpUnitClass(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + $tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replace( + '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(?!(?:self|static)::)(\w.*)$~m', + '$1\\\$2', + $tokens[$index]->getContent(), + )]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php new file mode 100644 index 0000000..7cec173 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * types?: list<'abstract'|'final'|'normal'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * types: list<'abstract'|'final'|'normal'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gert de Pagter + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHPUnit test classes should be marked as internal.', + [ + new CodeSample(" ['final']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before FinalInternalClassFixer, PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 68; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $types = ['normal', 'final', 'abstract']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('types', 'What types of classes to mark as internal.')) + ->setAllowedValues([new AllowedValueSubset($types)]) + ->setAllowedTypes(['string[]']) + ->setDefault(['normal', 'final']) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + + $prevIndex = $tokens->getPrevMeaningfulToken($classIndex); + if ($tokens[$prevIndex]->isGivenKind(\T_NEW)) { + return; // Skip instantiation of anonymous classes + } + + if (!$this->isAllowedByConfiguration($tokens, $classIndex)) { + return; + } + + $this->ensureIsDocBlockWithAnnotation( + $tokens, + $classIndex, + 'internal', + ['internal'], + [], + ); + } + + private function isAllowedByConfiguration(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + + if (isset($modifiers['final'])) { + return \in_array('final', $this->configuration['types'], true); + } + + if (isset($modifiers['abstract'])) { + return \in_array('abstract', $this->configuration['types'], true); + } + + return \in_array('normal', $this->configuration['types'], true); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php new file mode 100644 index 0000000..250cd62 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php @@ -0,0 +1,267 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case?: 'camel_case'|'snake_case', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case: 'camel_case'|'snake_case', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitMethodCasingFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const CAMEL_CASE = 'camel_case'; + + /** + * @internal + */ + public const SNAKE_CASE = 'snake_case'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Enforce camel (or snake) case for PHPUnit test methods, following configuration.', + [ + new CodeSample( + <<<'PHP' + self::SNAKE_CASE], + ), + new VersionSpecificCodeSample( + <<<'PHP' + self::SNAKE_CASE], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after PhpUnitTestAnnotationFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('case', 'Apply camel or snake case to test methods.')) + ->setAllowedValues([self::CAMEL_CASE, self::SNAKE_CASE]) + ->setDefault(self::CAMEL_CASE) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $existingFunctionNamesLowercase = []; + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (!$this->isMethod($tokens, $index)) { + continue; + } + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $existingFunctionNamesLowercase[strtolower($tokens[$functionNameIndex]->getContent())] = null; + } + unset($index); + + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (!$this->isTestMethod($tokens, $index)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + $functionNameLowercase = strtolower($functionName); + $newFunctionName = $this->updateMethodCasing($functionName); + $newFunctionNameLowercase = strtolower($newFunctionName); + if ( + \array_key_exists($newFunctionNameLowercase, $existingFunctionNamesLowercase) + && $functionNameLowercase !== $newFunctionNameLowercase + ) { + continue; + } + $existingFunctionNamesLowercase[$newFunctionNameLowercase] = null; + + if ($newFunctionName !== $functionName) { + $tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]); + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + $this->updateDocBlock($tokens, $docBlockIndex); + } + } + } + + private function updateMethodCasing(string $functionName): string + { + $parts = explode('::', $functionName); + + $functionNamePart = array_pop($parts); + + if (self::CAMEL_CASE === $this->configuration['case']) { + $newFunctionNamePart = $functionNamePart; + $newFunctionNamePart = ucwords($newFunctionNamePart, '_'); + $newFunctionNamePart = str_replace('_', '', $newFunctionNamePart); + $newFunctionNamePart = lcfirst($newFunctionNamePart); + } else { + $newFunctionNamePart = Utils::camelCaseToUnderscore($functionNamePart); + } + + $parts[] = $newFunctionNamePart; + + return implode('::', $parts); + } + + private function isTestMethod(Tokens $tokens, int $index): bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return false; + } + + // if the function name starts with test it's a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if (str_starts_with($functionName, 'test')) { + return true; + } + + if ($this->isTestAttributePresent($tokens, $index)) { + return true; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + return + $tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT) // If the function doesn't have test in its name, and no doc block, it's not a test + && str_contains($tokens[$docBlockIndex]->getContent(), '@test'); + } + + private function isMethod(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + + private function updateDocBlock(Tokens $tokens, int $docBlockIndex): void + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + + $docBlockNeedsUpdate = false; + for ($inc = 0; $inc < \count($lines); ++$inc) { + $lineContent = $lines[$inc]->getContent(); + if (!str_contains($lineContent, '@depends')) { + continue; + } + + $newLineContent = Preg::replaceCallback('/(@depends\s+)(.+)(\b)/', fn (array $matches): string => \sprintf( + '%s%s%s', + $matches[1], + $this->updateMethodCasing($matches[2]), + $matches[3], + ), $lineContent); + + if ($newLineContent !== $lineContent) { + $lines[$inc] = new Line($newLineContent); + $docBlockNeedsUpdate = true; + } + } + + if ($docBlockNeedsUpdate) { + $lines = implode('', $lines); + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php new file mode 100644 index 0000000..4318184 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '5.4'|'5.5'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '5.4'|'5.5'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitMockFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private bool $fixCreatePartialMock; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `->getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.', + [ + new CodeSample( + <<<'PHP' + getMockWithoutInvokingTheOriginalConstructor("Foo"); + $mock1 = $this->getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); + $mock1 = $this->getMock("Baz", ["aaa"], ["argument"]); // version with more than 2 params is not supported + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); // version with multiple params is not supported + } + } + + PHP, + ['target' => PhpUnitTargetVersion::VERSION_5_4], + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->fixCreatePartialMock = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_5); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals([\T_STRING, 'getMockWithoutInvokingTheOriginalConstructor'], false)) { + $tokens[$index] = new Token([\T_STRING, 'createMock']); + } elseif ($tokens[$index]->equals([\T_STRING, 'getMock'], false)) { + $openingParenthesis = $tokens->getNextMeaningfulToken($index); + $closingParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openingParenthesis); + + $argumentsCount = $argumentsAnalyzer->countArguments($tokens, $openingParenthesis, $closingParenthesis); + + if (1 === $argumentsCount) { + $tokens[$index] = new Token([\T_STRING, 'createMock']); + } elseif (2 === $argumentsCount && true === $this->fixCreatePartialMock) { + $tokens[$index] = new Token([\T_STRING, 'createPartialMock']); + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_5_4, PhpUnitTargetVersion::VERSION_5_5, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php new file mode 100644 index 0000000..033d707 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Michał Adamski + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitMockShortWillReturnFixer extends AbstractPhpUnitFixer +{ + private const RETURN_METHODS_MAP = [ + 'returnargument' => 'willReturnArgument', + 'returncallback' => 'willReturnCallback', + 'returnself' => 'willReturnSelf', + 'returnvalue' => 'willReturn', + 'returnvaluemap' => 'willReturnMap', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usage of PHPUnit\'s mock e.g. `->will($this->returnValue(..))` must be replaced by its shorter equivalent such as `->willReturn(...)`.', + [ + new CodeSample( + <<<'PHP' + createMock(Some::class); + $someMock->method("some")->will($this->returnSelf()); + $someMock->method("some")->will($this->returnValue("example")); + $someMock->method("some")->will($this->returnArgument(2)); + $someMock->method("some")->will($this->returnCallback("str_rot13")); + $someMock->method("some")->will($this->returnValueMap(["a","b","c"])); + } + } + + PHP, + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $functionToReplaceIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$functionToReplaceIndex]->equals([\T_STRING, 'will'], false)) { + continue; + } + + $functionToReplaceOpeningBraceIndex = $tokens->getNextMeaningfulToken($functionToReplaceIndex); + + if (!$tokens[$functionToReplaceOpeningBraceIndex]->equals('(')) { + continue; + } + + $classReferenceIndex = $tokens->getNextMeaningfulToken($functionToReplaceOpeningBraceIndex); + $objectOperatorIndex = $tokens->getNextMeaningfulToken($classReferenceIndex); + $functionToRemoveIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex); + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $functionToRemoveIndex)) { + continue; + } + + if (!\array_key_exists(strtolower($tokens[$functionToRemoveIndex]->getContent()), self::RETURN_METHODS_MAP)) { + continue; + } + + $openingBraceIndex = $tokens->getNextMeaningfulToken($functionToRemoveIndex); + + if ($tokens[$tokens->getNextMeaningfulToken($openingBraceIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + continue; + } + + $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openingBraceIndex); + + $tokens[$functionToReplaceIndex] = new Token([\T_STRING, self::RETURN_METHODS_MAP[strtolower($tokens[$functionToRemoveIndex]->getContent())]]); + $tokens->clearTokenAndMergeSurroundingWhitespace($classReferenceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($objectOperatorIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionToRemoveIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openingBraceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($closingBraceIndex); + + $commaAfterClosingBraceIndex = $tokens->getNextMeaningfulToken($closingBraceIndex); + if ($tokens[$commaAfterClosingBraceIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaAfterClosingBraceIndex); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php new file mode 100644 index 0000000..c44ffda --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php @@ -0,0 +1,249 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '4.8'|'5.7'|'6.0'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '4.8'|'5.7'|'6.0'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitNamespacedFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private string $originalClassRegEx; + + /** + * Class Mappings. + * + * * [original classname => new classname] Some classes which match the + * original class regular expression do not have a same-compound name- + * space class and need a dedicated translation table. This trans- + * lation table is defined in @see configure. + * + * @var array Class Mappings + */ + private array $classMap; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'PHP' + PhpUnitTargetVersion::VERSION_4_8]), + ], + "PHPUnit v6 has finally fully switched to namespaces.\n" + ."You could start preparing the upgrade by switching from non-namespaced TestCase to namespaced one.\n" + .'Forward compatibility layer (`\PHPUnit\Framework\TestCase` class) was backported to PHPUnit v4.8.35 and PHPUnit v5.4.0.'."\n" + .'Extended forward compatibility layer (`PHPUnit\Framework\Assert`, `PHPUnit\Framework\BaseTestListener`, `PHPUnit\Framework\TestListener` classes) was introduced in v5.7.0.'."\n", + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + + /** + * {@inheritdoc} + * + * Must run before NoUnneededImportAliasFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_6_0)) { + $this->originalClassRegEx = '/^PHPUnit_\w+$/i'; + // @noinspection ClassConstantCanBeUsedInspection + $this->classMap = [ + 'PHPUnit_Extensions_PhptTestCase' => 'PHPUnit\Runner\PhptTestCase', + 'PHPUnit_Framework_Constraint' => 'PHPUnit\Framework\Constraint\Constraint', + 'PHPUnit_Framework_Constraint_StringMatches' => 'PHPUnit\Framework\Constraint\StringMatchesFormatDescription', + 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => 'PHPUnit\Framework\Constraint\JsonMatchesErrorMessageProvider', + 'PHPUnit_Framework_Constraint_PCREMatch' => 'PHPUnit\Framework\Constraint\RegularExpression', + 'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => 'PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression', + 'PHPUnit_Framework_Constraint_And' => 'PHPUnit\Framework\Constraint\LogicalAnd', + 'PHPUnit_Framework_Constraint_Or' => 'PHPUnit\Framework\Constraint\LogicalOr', + 'PHPUnit_Framework_Constraint_Not' => 'PHPUnit\Framework\Constraint\LogicalNot', + 'PHPUnit_Framework_Constraint_Xor' => 'PHPUnit\Framework\Constraint\LogicalXor', + 'PHPUnit_Framework_Error' => 'PHPUnit\Framework\Error\Error', + 'PHPUnit_Framework_TestSuite_DataProvider' => 'PHPUnit\Framework\DataProviderTestSuite', + 'PHPUnit_Framework_MockObject_Invocation_Static' => 'PHPUnit\Framework\MockObject\Invocation\StaticInvocation', + 'PHPUnit_Framework_MockObject_Invocation_Object' => 'PHPUnit\Framework\MockObject\Invocation\ObjectInvocation', + 'PHPUnit_Framework_MockObject_Stub_Return' => 'PHPUnit\Framework\MockObject\Stub\ReturnStub', + 'PHPUnit_Runner_Filter_Group_Exclude' => 'PHPUnit\Runner\Filter\ExcludeGroupFilterIterator', + 'PHPUnit_Runner_Filter_Group_Include' => 'PHPUnit\Runner\Filter\IncludeGroupFilterIterator', + 'PHPUnit_Runner_Filter_Test' => 'PHPUnit\Runner\Filter\NameFilterIterator', + 'PHPUnit_Util_PHP' => 'PHPUnit\Util\PHP\AbstractPhpProcess', + 'PHPUnit_Util_PHP_Default' => 'PHPUnit\Util\PHP\DefaultPhpProcess', + 'PHPUnit_Util_PHP_Windows' => 'PHPUnit\Util\PHP\WindowsPhpProcess', + 'PHPUnit_Util_Regex' => 'PHPUnit\Util\RegularExpression', + 'PHPUnit_Util_TestDox_ResultPrinter_XML' => 'PHPUnit\Util\TestDox\XmlResultPrinter', + 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => 'PHPUnit\Util\TestDox\HtmlResultPrinter', + 'PHPUnit_Util_TestDox_ResultPrinter_Text' => 'PHPUnit\Util\TestDox\TextResultPrinter', + 'PHPUnit_Util_TestSuiteIterator' => 'PHPUnit\Framework\TestSuiteIterator', + 'PHPUnit_Util_XML' => 'PHPUnit\Util\Xml', + ]; + } elseif (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_7)) { + $this->originalClassRegEx = '/^PHPUnit_Framework_(TestCase|Assert|BaseTestListener|TestListener)+$/i'; + $this->classMap = []; + } else { + $this->originalClassRegEx = '/^PHPUnit_Framework_TestCase$/i'; + $this->classMap = []; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $importedOriginalClassesMap = []; + $currIndex = 0; + + while (true) { + $currIndex = $tokens->getNextTokenOfKind($currIndex, [[\T_STRING]]); + + if (null === $currIndex) { + break; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + + if ($tokens[$prevIndex]->isGivenKind([\T_CONST, \T_DOUBLE_COLON])) { + continue; + } + + $originalClass = $tokens[$currIndex]->getContent(); + $allowedReplacementScenarios = (new ClassyAnalyzer())->isClassyInvocation($tokens, $currIndex) + || $this->isImport($tokens, $currIndex); + + if (!$allowedReplacementScenarios || !Preg::match($this->originalClassRegEx, $originalClass)) { + ++$currIndex; + + continue; + } + + $substituteTokens = $this->generateReplacement($originalClass); + + $tokens->clearAt($currIndex); + $tokens->insertAt( + $currIndex, + isset($importedOriginalClassesMap[$originalClass]) ? $substituteTokens[$substituteTokens->getSize() - 1] : $substituteTokens, + ); + + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + if ($tokens[$prevIndex]->isGivenKind(\T_USE)) { + $importedOriginalClassesMap[$originalClass] = true; + } elseif ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + + if ($tokens[$prevIndex]->isGivenKind(\T_USE)) { + $importedOriginalClassesMap[$originalClass] = true; + } + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_4_8, PhpUnitTargetVersion::VERSION_5_7, PhpUnitTargetVersion::VERSION_6_0, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + ]); + } + + private function generateReplacement(string $originalClassName): Tokens + { + $delimiter = '_'; + $string = $originalClassName; + + $map = array_change_key_case($this->classMap); + if (isset($map[strtolower($originalClassName)])) { + $delimiter = '\\'; + $string = $map[strtolower($originalClassName)]; + } + + $parts = explode($delimiter, $string); + $tokensArray = []; + + while ([] !== $parts) { + $tokensArray[] = new Token([\T_STRING, array_shift($parts)]); + if ([] !== $parts) { + $tokensArray[] = new Token([\T_NS_SEPARATOR, '\\']); + } + } + + return Tokens::fromArray($tokensArray); + } + + private function isImport(Tokens $tokens, int $currIndex): bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + return $tokens[$prevIndex]->isGivenKind(\T_USE); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php new file mode 100644 index 0000000..92fc93b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php @@ -0,0 +1,287 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * target?: '3.2'|'4.3'|'newest', + * use_class_const?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * target: '3.2'|'4.3'|'newest', + * use_class_const: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitNoExpectationAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private bool $fixMessageRegExp; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Usages of `@expectedException*` annotations MUST be replaced by `->setExpectedException*` methods.', + [ + new CodeSample( + <<<'PHP' + PhpUnitTargetVersion::VERSION_3_2], + ), + ], + null, + 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitExpectationFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isRisky(): bool + { + return true; + } + + protected function configurePostNormalisation(): void + { + $this->fixMessageRegExp = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_4_3); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([PhpUnitTargetVersion::VERSION_3_2, PhpUnitTargetVersion::VERSION_4_3, PhpUnitTargetVersion::VERSION_NEWEST]) + ->setDefault(PhpUnitTargetVersion::VERSION_NEWEST) + ->getOption(), + (new FixerOptionBuilder('use_class_const', 'Use ::class notation.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (!$tokens[$i]->isGivenKind(\T_FUNCTION) || $tokensAnalyzer->isLambda($i)) { + continue; + } + + $functionIndex = $i; + $docBlockIndex = $i; + + // ignore abstract functions + $braceIndex = $tokens->getNextTokenOfKind($functionIndex, [';', '{']); + if (!$tokens[$braceIndex]->equals('{')) { + continue; + } + + do { + $docBlockIndex = $tokens->getPrevNonWhitespace($docBlockIndex); + } while ($tokens[$docBlockIndex]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT])); + + if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $annotations = []; + + foreach ($doc->getAnnotationsOfType([ + 'expectedException', + 'expectedExceptionCode', + 'expectedExceptionMessage', + 'expectedExceptionMessageRegExp', + ]) as $annotation) { + $tag = $annotation->getTag()->getName(); + $content = $this->extractContentFromAnnotation($annotation); + $annotations[$tag] = $content; + $annotation->remove(); + } + + if (!isset($annotations['expectedException'])) { + continue; + } + + if (!$this->fixMessageRegExp && isset($annotations['expectedExceptionMessageRegExp'])) { + continue; + } + + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + + $paramList = $this->annotationsToParamList($annotations); + + $newMethodsCode = '' + .(isset($annotations['expectedExceptionMessageRegExp']) ? 'setExpectedExceptionRegExp' : 'setExpectedException') + .'(' + .implode(', ', $paramList) + .');'; + $newMethods = Tokens::fromCode($newMethodsCode); + $newMethods[0] = new Token([ + \T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$originalIndent.$this->whitespacesConfig->getIndent(), + ]); + + // apply changes + $docContent = $doc->getContent(); + if ('' === $docContent) { + $docContent = '/** */'; + } + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $docContent]); + $tokens->insertAt($braceIndex + 1, $newMethods); + + $whitespaceIndex = $braceIndex + $newMethods->getSize() + 1; + $tokens[$whitespaceIndex] = new Token([ + \T_WHITESPACE, + $this->whitespacesConfig->getLineEnding().$tokens[$whitespaceIndex]->getContent(), + ]); + + $i = $docBlockIndex; + } + } + + private function extractContentFromAnnotation(Annotation $annotation): string + { + $tag = $annotation->getTag()->getName(); + + if (!Preg::match('/@'.$tag.'\s+(.+)$/s', $annotation->getContent(), $matches)) { + return ''; + } + + \assert(isset($matches[1])); + $content = Preg::replace('/\*+\/$/', '', $matches[1]); + + if (Preg::match('/\R/u', $content)) { + $content = Preg::replace('/\s*\R+\s*\*\s*/u', ' ', $content); + } + + return rtrim($content); + } + + /** + * @param array $annotations + * + * @return non-empty-list + */ + private function annotationsToParamList(array $annotations): array + { + $params = []; + \assert(isset($annotations['expectedException'])); + $exceptionClass = ltrim($annotations['expectedException'], '\\'); + + if (str_contains($exceptionClass, '*')) { + \assert(\is_int(strpos($exceptionClass, '*'))); + $exceptionClass = substr($exceptionClass, 0, strpos($exceptionClass, '*')); + } + + $exceptionClass = trim($exceptionClass); + + if (true === $this->configuration['use_class_const']) { + $params[] = "\\{$exceptionClass}::class"; + } else { + $params[] = "'{$exceptionClass}'"; + } + + if (isset($annotations['expectedExceptionMessage'])) { + $params[] = var_export($annotations['expectedExceptionMessage'], true); + } elseif (isset($annotations['expectedExceptionMessageRegExp'])) { + $params[] = var_export($annotations['expectedExceptionMessageRegExp'], true); + } elseif (isset($annotations['expectedExceptionCode'])) { + $params[] = 'null'; + } + + if (isset($annotations['expectedExceptionCode'])) { + $params[] = $annotations['expectedExceptionCode']; + } + + return $params; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php new file mode 100644 index 0000000..45266c1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php @@ -0,0 +1,115 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Gert de Pagter + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitSetUpTearDownVisibilityFixer extends AbstractPhpUnitFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Changes the visibility of the `setUp()` and `tearDown()` functions of PHPUnit to `protected`, to match the PHPUnit TestCase.', + [ + new CodeSample( + <<<'PHP' + hello = "hello"; + } + + public function tearDown() + { + $this->hello = null; + } + } + + PHP, + ), + ], + null, + 'This fixer may change functions named `setUp()` or `tearDown()` outside of PHPUnit tests, ' + .'when a class is wrongly seen as a PHPUnit test.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $counter = 0; + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $slicesToInsert = []; + + for ($index = $startIndex + 1; $index < $endIndex; ++$index) { + if (2 === $counter) { + break; // we've seen both methods we are interested in, so stop analyzing this class + } + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = strtolower($tokens[$functionNameIndex]->getContent()); + + if ('setup' !== $functionName && 'teardown' !== $functionName) { + continue; + } + + ++$counter; + + $visibility = $tokensAnalyzer->getMethodAttributes($index)['visibility']; + + if (\T_PUBLIC === $visibility) { + $visibilityIndex = $tokens->getPrevTokenOfKind($index, [[\T_PUBLIC]]); + $tokens[$visibilityIndex] = new Token([\T_PROTECTED, 'protected']); + + continue; + } + + if (null === $visibility) { + $slicesToInsert[$index] = [new Token([\T_PROTECTED, 'protected']), new Token([\T_WHITESPACE, ' '])]; + } + } + + $tokens->insertSlices($slicesToInsert); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php new file mode 100644 index 0000000..bcef2e4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php @@ -0,0 +1,109 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * group?: 'large'|'medium'|'small', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * group: 'large'|'medium'|'small', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Jefersson Nathan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitSizeClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const SIZES = ['small', 'medium', 'large']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHPUnit test cases should have `@small`, `@medium` or `@large` annotation to enable run time limits.', + [ + new CodeSample(" 'medium']), + ], + 'The special groups [small, medium, large] provides a way to identify tests that are taking long to be executed.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitAttributesFixer, PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 9; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('group', 'Define a specific group to be used in case no group is already in use.')) + ->setAllowedValues(self::SIZES) + ->setDefault('small') + ->getOption(), + ]); + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + + if ($this->isAbstractClass($tokens, $classIndex)) { + return; + } + + $this->ensureIsDocBlockWithAnnotation( + $tokens, + $classIndex, + $this->configuration['group'], + self::SIZES, + [ + 'phpunit\framework\attributes\small', + 'phpunit\framework\attributes\medium', + 'phpunit\framework\attributes\large', + ], + ); + } + + private function isAbstractClass(Tokens $tokens, int $i): bool + { + $typeIndex = $tokens->getPrevMeaningfulToken($i); + + return $tokens[$typeIndex]->isGivenKind(\T_ABSTRACT); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php new file mode 100644 index 0000000..2e1c013 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php @@ -0,0 +1,160 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * assertions?: list<'assertAttributeEquals'|'assertAttributeNotEquals'|'assertEquals'|'assertNotEquals'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * assertions: list<'assertAttributeEquals'|'assertAttributeNotEquals'|'assertEquals'|'assertNotEquals'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private const ASSERTION_MAP = [ + 'assertAttributeEquals' => 'assertAttributeSame', + 'assertAttributeNotEquals' => 'assertAttributeNotSame', + 'assertEquals' => 'assertSame', + 'assertNotEquals' => 'assertNotSame', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPUnit methods like `assertSame` should be used instead of `assertEquals`.', + [ + new CodeSample( + <<<'PHP' + assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } + } + + PHP, + ), + new CodeSample( + <<<'PHP' + assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } + } + + PHP, + ['assertions' => ['assertEquals']], + ), + ], + null, + 'Risky when any of the functions are overridden or when testing object equality.', + ); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach ($this->configuration['assertions'] as $methodBefore) { + $methodAfter = self::ASSERTION_MAP[$methodBefore]; + + for ($index = $startIndex; $index < $endIndex; ++$index) { + $methodIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING, $methodBefore]]); + + if (null === $methodIndex) { + break; + } + + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $methodIndex)) { + continue; + } + + $openingParenthesisIndex = $tokens->getNextMeaningfulToken($methodIndex); + $argumentsCount = $argumentsAnalyzer->countArguments( + $tokens, + $openingParenthesisIndex, + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openingParenthesisIndex), + ); + + if (2 === $argumentsCount || 3 === $argumentsCount) { + $tokens[$methodIndex] = new Token([\T_STRING, $methodAfter]); + } + + $index = $methodIndex; + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(array_keys(self::ASSERTION_MAP))]) + ->setDefault([ + 'assertAttributeEquals', + 'assertAttributeNotEquals', + 'assertEquals', + 'assertNotEquals', + ]) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php new file mode 100644 index 0000000..aec1ed9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use Composer\Semver\Comparator; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitTargetVersion +{ + public const VERSION_3_0 = '3.0'; + public const VERSION_3_2 = '3.2'; + public const VERSION_3_5 = '3.5'; + public const VERSION_4_3 = '4.3'; + public const VERSION_4_8 = '4.8'; + public const VERSION_5_0 = '5.0'; + public const VERSION_5_2 = '5.2'; + public const VERSION_5_4 = '5.4'; + public const VERSION_5_5 = '5.5'; + public const VERSION_5_6 = '5.6'; + public const VERSION_5_7 = '5.7'; + public const VERSION_6_0 = '6.0'; + public const VERSION_7_5 = '7.5'; + public const VERSION_8_4 = '8.4'; + public const VERSION_9_1 = '9.1'; + public const VERSION_10_0 = '10.0'; + public const VERSION_11_0 = '11.0'; + public const VERSION_NEWEST = 'newest'; + + private function __construct() {} + + public static function fulfills(string $candidate, string $target): bool + { + if (self::VERSION_NEWEST === $target) { + throw new \LogicException(\sprintf('Parameter `target` shall not be provided as "%s", determine proper target for tested PHPUnit feature instead.', self::VERSION_NEWEST)); + } + + if (self::VERSION_NEWEST === $candidate) { + return true; + } + + return Comparator::greaterThanOrEqualTo($candidate, $target); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php new file mode 100644 index 0000000..fb6f461 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php @@ -0,0 +1,415 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * style?: 'annotation'|'prefix', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * style: 'annotation'|'prefix', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gert de Pagter + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitTestAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds or removes @test annotations from tests, following configuration.', + [ + new CodeSample( + <<<'PHP' + whitespacesConfig->getLineEnding(), + ), + new CodeSample( + <<<'PHP' + whitespacesConfig->getLineEnding(), + ['style' => 'annotation'], + ), + ], + null, + 'This fixer may change the name of your tests, and could cause incompatibility with' + .' abstract classes or interfaces.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitMethodCasingFixer, PhpdocTrimFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + if ('annotation' === $this->configuration['style']) { + $this->applyTestAnnotation($tokens, $startIndex, $endIndex); + } else { + $this->applyTestPrefix($tokens, $startIndex, $endIndex); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('style', 'Whether to use the @test annotation or not.')) + ->setAllowedValues(['prefix', 'annotation']) + ->setDefault('prefix') + ->getOption(), + ]); + } + + private function applyTestAnnotation(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (!$this->isTestMethod($tokens, $i)) { + continue; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($i); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName) && !$this->hasProperTestAnnotation($tokens, $i)) { + $newFunctionName = $this->removeTestPrefix($functionName); + $tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]); + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $i); + + if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + $lines = $this->updateDocBlock($tokens, $docBlockIndex); + $lines = $this->addTestAnnotation($lines, $tokens, $docBlockIndex); + $lines = implode('', $lines); + + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); + } else { + // Create a new docblock if it didn't have one before; + $this->createDocBlock($tokens, $docBlockIndex, 'test'); + } + } + } + + private function applyTestPrefix(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + // We explicitly check again if the function has a doc block to save some time. + if (!$this->isTestMethod($tokens, $i)) { + continue; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $i); + + if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $lines = $this->updateDocBlock($tokens, $docBlockIndex); + $lines = implode('', $lines); + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); + + $functionNameIndex = $tokens->getNextMeaningfulToken($i); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName)) { + continue; + } + + $newFunctionName = $this->addTestPrefix($functionName); + $tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]); + } + } + + private function isTestMethod(Tokens $tokens, int $index): bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return false; + } + + // if the function name starts with test it is a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + + if ($this->hasTestPrefix($functionName)) { + return true; + } + + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + + // If the function doesn't have test in its name, and no doc block, it is not a test + return + $tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT) + && str_contains($tokens[$docBlockIndex]->getContent(), '@test'); + } + + private function isMethod(Tokens $tokens, int $index): bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + + private function hasTestPrefix(string $functionName): bool + { + return str_starts_with($functionName, 'test'); + } + + private function hasProperTestAnnotation(Tokens $tokens, int $index): bool + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + $doc = $tokens[$docBlockIndex]->getContent(); + + return Preg::match('/\*\s+@test\b/', $doc); + } + + private function removeTestPrefix(string $functionName): string + { + $remainder = Preg::replace('/^test(?=[A-Z_])_?/', '', $functionName); + + if ('' === $remainder) { + return $functionName; + } + + return lcfirst($remainder); + } + + private function addTestPrefix(string $functionName): string + { + return 'test'.ucfirst($functionName); + } + + /** + * @return list + */ + private function updateDocBlock(Tokens $tokens, int $docBlockIndex): array + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + + /** + * @param list $lines + * + * @return list + */ + private function updateLines(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $needsAnnotation = 'annotation' === $this->configuration['style']; + + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + foreach ($lines as $i => $line) { + // If we need to add test annotation and it is a single line comment we need to deal with that separately + if ($needsAnnotation && ($line->isTheStart() && $line->isTheEnd())) { + if (!$this->doesDocBlockContainTest($doc)) { + $lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex); + + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + // One we split it up, we run the function again, so we deal with other things in a proper way + } + + if (!$needsAnnotation + && str_contains($line->getContent(), ' @test') + && !str_contains($line->getContent(), '@testWith') + && !str_contains($line->getContent(), '@testdox') + ) { + // We remove @test from the doc block + $lines[$i] = $line = new Line(str_replace(' @test', '', $line->getContent())); + } + // ignore the line if it isn't @depends + if (!str_contains($line->getContent(), '@depends')) { + continue; + } + + $lines[$i] = $this->updateDependsAnnotation($line); + } + + return $lines; + } + + /** + * Take a one line doc block, and turn it into a multi line doc block. + * + * @param non-empty-list $lines + * + * @return non-empty-list + */ + private function splitUpDocBlock(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $lineContent = $this->getSingleLineDocBlockEntry($lines); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + + return [ + new Line('/**'.$lineEnd), + new Line($originalIndent.' * '.$lineContent.$lineEnd), + new Line($originalIndent.' */'), + ]; + } + + /** + * @TODO check whether it's doable to use \PhpCsFixer\DocBlock\DocBlock::getSingleLineDocBlockEntry instead + * + * @param non-empty-list $lines + */ + private function getSingleLineDocBlockEntry(array $lines): string + { + $line = $lines[0]; + $line = str_replace('*/', '', $line->getContent()); + $line = trim($line); + $line = str_split($line); + $i = \count($line); + do { + --$i; + } while ('*' !== $line[$i] && '*' !== $line[$i - 1] && '/' !== $line[$i - 2]); + if (' ' === $line[$i]) { + ++$i; + } + $line = \array_slice($line, $i); + + return implode('', $line); + } + + /** + * Updates the depends tag on the current doc block. + */ + private function updateDependsAnnotation(Line $line): Line + { + if ('annotation' === $this->configuration['style']) { + return $this->removeTestPrefixFromDependsAnnotation($line); + } + + return $this->addTestPrefixToDependsAnnotation($line); + } + + private function removeTestPrefixFromDependsAnnotation(Line $line): Line + { + $line = str_split($line->getContent()); + + $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); + $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); + + if ($this->hasTestPrefix($dependsFunctionName)) { + $dependsFunctionName = $this->removeTestPrefix($dependsFunctionName); + } + array_splice($line, $dependsIndex); + + return new Line(implode('', $line).$dependsFunctionName); + } + + private function addTestPrefixToDependsAnnotation(Line $line): Line + { + $line = str_split($line->getContent()); + $dependsIndex = $this->findWhereDependsFunctionNameStarts($line); + $dependsFunctionName = implode('', \array_slice($line, $dependsIndex)); + + if (!$this->hasTestPrefix($dependsFunctionName)) { + $dependsFunctionName = $this->addTestPrefix($dependsFunctionName); + } + + array_splice($line, $dependsIndex); + + return new Line(implode('', $line).$dependsFunctionName); + } + + /** + * Helps to find where the function name in the doc block starts. + * + * @param list $line + */ + private function findWhereDependsFunctionNameStarts(array $line): int + { + $index = (int) stripos(implode('', $line), '@depends') + 8; + + while (' ' === $line[$index]) { + ++$index; + } + + return $index; + } + + /** + * @param list $lines + * + * @return list + */ + private function addTestAnnotation(array $lines, Tokens $tokens, int $docBlockIndex): array + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + + if (!$this->doesDocBlockContainTest($doc)) { + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + + array_splice($lines, -1, 0, [new Line($originalIndent.' *'.$lineEnd.$originalIndent.' * @test'.$lineEnd)]); + \assert(array_is_list($lines)); // we know it's list, but we need to tell PHPStan + } + + return $lines; + } + + private function doesDocBlockContainTest(DocBlock $doc): bool + { + return 0 !== \count($doc->getAnnotationsOfType('test')); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php new file mode 100644 index 0000000..19d4e80 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php @@ -0,0 +1,646 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * call_type?: 'self'|'static'|'this', + * methods?: array, + * target?: '10.0'|'11.0'|'newest', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * call_type: 'self'|'static'|'this', + * methods: array, + * target: '10.0'|'11.0'|'newest', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @phpstan-import-type _PhpTokenArray from Token + * + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitTestCaseStaticMethodCallsFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const CALL_TYPE_THIS = 'this'; + + /** + * @internal + */ + public const CALL_TYPE_SELF = 'self'; + + /** + * @internal + */ + public const CALL_TYPE_STATIC = 'static'; + + /** + * @var array + */ + private const METHODS = [ + // Assert methods + 'anything' => true, + 'arrayHasKey' => true, + 'assertArrayHasKey' => true, + 'assertArrayIsEqualToArrayIgnoringListOfKeys' => true, + 'assertArrayIsEqualToArrayOnlyConsideringListOfKeys' => true, + 'assertArrayIsIdenticalToArrayIgnoringListOfKeys' => true, + 'assertArrayIsIdenticalToArrayOnlyConsideringListOfKeys' => true, + 'assertArrayNotHasKey' => true, + 'assertArraySubset' => true, + 'assertArraysAreIdentical' => true, + 'assertArraysAreIdenticalIgnoringOrder' => true, + 'assertArraysHaveIdenticalValues' => true, + 'assertArraysHaveIdenticalValuesIgnoringOrder' => true, + 'assertArraysAreEqual' => true, + 'assertArraysAreEqualIgnoringOrder' => true, + 'assertArraysHaveEqualValues' => true, + 'assertArraysHaveEqualValuesIgnoringOrder' => true, + 'assertAttributeContains' => true, + 'assertAttributeContainsOnly' => true, + 'assertAttributeCount' => true, + 'assertAttributeEmpty' => true, + 'assertAttributeEquals' => true, + 'assertAttributeGreaterThan' => true, + 'assertAttributeGreaterThanOrEqual' => true, + 'assertAttributeInstanceOf' => true, + 'assertAttributeInternalType' => true, + 'assertAttributeLessThan' => true, + 'assertAttributeLessThanOrEqual' => true, + 'assertAttributeNotContains' => true, + 'assertAttributeNotContainsOnly' => true, + 'assertAttributeNotCount' => true, + 'assertAttributeNotEmpty' => true, + 'assertAttributeNotEquals' => true, + 'assertAttributeNotInstanceOf' => true, + 'assertAttributeNotInternalType' => true, + 'assertAttributeNotSame' => true, + 'assertAttributeSame' => true, + 'assertClassHasAttribute' => true, + 'assertClassHasStaticAttribute' => true, + 'assertClassNotHasAttribute' => true, + 'assertClassNotHasStaticAttribute' => true, + 'assertContains' => true, + 'assertContainsEquals' => true, + 'assertContainsNotOnlyArray' => true, + 'assertContainsNotOnlyBool' => true, + 'assertContainsNotOnlyCallable' => true, + 'assertContainsNotOnlyClosedResource' => true, + 'assertContainsNotOnlyFloat' => true, + 'assertContainsNotOnlyInstancesOf' => true, + 'assertContainsNotOnlyInt' => true, + 'assertContainsNotOnlyIterable' => true, + 'assertContainsNotOnlyNull' => true, + 'assertContainsNotOnlyNumeric' => true, + 'assertContainsNotOnlyObject' => true, + 'assertContainsNotOnlyResource' => true, + 'assertContainsNotOnlyScalar' => true, + 'assertContainsNotOnlyString' => true, + 'assertContainsOnly' => true, + 'assertContainsOnlyArray' => true, + 'assertContainsOnlyBool' => true, + 'assertContainsOnlyCallable' => true, + 'assertContainsOnlyClosedResource' => true, + 'assertContainsOnlyFloat' => true, + 'assertContainsOnlyInstancesOf' => true, + 'assertContainsOnlyInt' => true, + 'assertContainsOnlyIterable' => true, + 'assertContainsOnlyNull' => true, + 'assertContainsOnlyNumeric' => true, + 'assertContainsOnlyObject' => true, + 'assertContainsOnlyResource' => true, + 'assertContainsOnlyScalar' => true, + 'assertContainsOnlyString' => true, + 'assertCount' => true, + 'assertDirectoryDoesNotExist' => true, + 'assertDirectoryExists' => true, + 'assertDirectoryIsNotReadable' => true, + 'assertDirectoryIsNotWritable' => true, + 'assertDirectoryIsReadable' => true, + 'assertDirectoryIsWritable' => true, + 'assertDirectoryNotExists' => true, + 'assertDirectoryNotIsReadable' => true, + 'assertDirectoryNotIsWritable' => true, + 'assertDoesNotMatchRegularExpression' => true, + 'assertEmpty' => true, + 'assertEquals' => true, + 'assertEqualsCanonicalizing' => true, + 'assertEqualsIgnoringCase' => true, + 'assertEqualsWithDelta' => true, + 'assertEqualXMLStructure' => true, + 'assertFalse' => true, + 'assertFileDoesNotExist' => true, + 'assertFileEquals' => true, + 'assertFileEqualsCanonicalizing' => true, + 'assertFileEqualsFileIgnoringWhitespace' => true, + 'assertFileEqualsIgnoringCase' => true, + 'assertFileExists' => true, + 'assertFileIsNotReadable' => true, + 'assertFileIsNotWritable' => true, + 'assertFileIsReadable' => true, + 'assertFileIsWritable' => true, + 'assertFileMatchesFormat' => true, + 'assertFileMatchesFormatFile' => true, + 'assertFileNotEquals' => true, + 'assertFileNotEqualsCanonicalizing' => true, + 'assertFileNotEqualsFileIgnoringWhitespace' => true, + 'assertFileNotEqualsIgnoringCase' => true, + 'assertFileNotExists' => true, + 'assertFileNotIsReadable' => true, + 'assertFileNotIsWritable' => true, + 'assertFinite' => true, + 'assertGreaterThan' => true, + 'assertGreaterThanOrEqual' => true, + 'assertInfinite' => true, + 'assertInstanceOf' => true, + 'assertInternalType' => true, + 'assertIsArray' => true, + 'assertIsBool' => true, + 'assertIsCallable' => true, + 'assertIsClosedResource' => true, + 'assertIsFloat' => true, + 'assertIsInt' => true, + 'assertIsIterable' => true, + 'assertIsList' => true, + 'assertIsNotArray' => true, + 'assertIsNotBool' => true, + 'assertIsNotCallable' => true, + 'assertIsNotClosedResource' => true, + 'assertIsNotFloat' => true, + 'assertIsNotInt' => true, + 'assertIsNotIterable' => true, + 'assertIsNotNumeric' => true, + 'assertIsNotObject' => true, + 'assertIsNotReadable' => true, + 'assertIsNotResource' => true, + 'assertIsNotScalar' => true, + 'assertIsNotString' => true, + 'assertIsNotWritable' => true, + 'assertIsNumeric' => true, + 'assertIsObject' => true, + 'assertIsReadable' => true, + 'assertIsResource' => true, + 'assertIsScalar' => true, + 'assertIsString' => true, + 'assertIsWritable' => true, + 'assertJson' => true, + 'assertJsonFileEqualsJsonFile' => true, + 'assertJsonFileNotEqualsJsonFile' => true, + 'assertJsonStringEqualsJsonFile' => true, + 'assertJsonStringEqualsJsonString' => true, + 'assertJsonStringNotEqualsJsonFile' => true, + 'assertJsonStringNotEqualsJsonString' => true, + 'assertLessThan' => true, + 'assertLessThanOrEqual' => true, + 'assertMatchesRegularExpression' => true, + 'assertNan' => true, + 'assertNotContains' => true, + 'assertNotContainsEquals' => true, + 'assertNotContainsOnly' => true, + 'assertNotCount' => true, + 'assertNotEmpty' => true, + 'assertNotEquals' => true, + 'assertNotEqualsCanonicalizing' => true, + 'assertNotEqualsIgnoringCase' => true, + 'assertNotEqualsWithDelta' => true, + 'assertNotFalse' => true, + 'assertNotInstanceOf' => true, + 'assertNotInternalType' => true, + 'assertNotIsReadable' => true, + 'assertNotIsWritable' => true, + 'assertNotNull' => true, + 'assertNotRegExp' => true, + 'assertNotSame' => true, + 'assertNotSameSize' => true, + 'assertNotTrue' => true, + 'assertNull' => true, + 'assertObjectEquals' => true, + 'assertObjectHasAttribute' => true, + 'assertObjectHasProperty' => true, + 'assertObjectNotEquals' => true, + 'assertObjectNotHasAttribute' => true, + 'assertObjectNotHasProperty' => true, + 'assertRegExp' => true, + 'assertSame' => true, + 'assertSameSize' => true, + 'assertStringContainsString' => true, + 'assertStringContainsStringIgnoringCase' => true, + 'assertStringContainsStringIgnoringLineEndings' => true, + 'assertStringEndsNotWith' => true, + 'assertStringEndsWith' => true, + 'assertStringEqualsFile' => true, + 'assertStringEqualsFileCanonicalizing' => true, + 'assertStringEqualsFileIgnoringCase' => true, + 'assertStringEqualsFileIgnoringWhitespace' => true, + 'assertStringEqualsStringIgnoringLineEndings' => true, + 'assertStringEqualsStringIgnoringWhitespace' => true, + 'assertStringMatchesFormat' => true, + 'assertStringMatchesFormatFile' => true, + 'assertStringNotContainsString' => true, + 'assertStringNotContainsStringIgnoringCase' => true, + 'assertStringNotEqualsFile' => true, + 'assertStringNotEqualsFileCanonicalizing' => true, + 'assertStringNotEqualsFileIgnoringCase' => true, + 'assertStringNotEqualsFileIgnoringWhitespace' => true, + 'assertStringNotEqualsStringIgnoringWhitespace' => true, + 'assertStringNotMatchesFormat' => true, + 'assertStringNotMatchesFormatFile' => true, + 'assertStringStartsNotWith' => true, + 'assertStringStartsWith' => true, + 'assertThat' => true, + 'assertTrue' => true, + 'assertXmlFileEqualsXmlFile' => true, + 'assertXmlFileEqualsXmlFileConsideringComments' => true, + 'assertXmlFileNotEqualsXmlFile' => true, + 'assertXmlFileNotEqualsXmlFileConsideringComments' => true, + 'assertXmlStringEqualsXmlFile' => true, + 'assertXmlStringEqualsXmlFileConsideringComments' => true, + 'assertXmlStringEqualsXmlString' => true, + 'assertXmlStringEqualsXmlStringConsideringComments' => true, + 'assertXmlStringNotEqualsXmlFile' => true, + 'assertXmlStringNotEqualsXmlFileConsideringComments' => true, + 'assertXmlStringNotEqualsXmlString' => true, + 'assertXmlStringNotEqualsXmlStringConsideringComments' => true, + 'attribute' => true, + 'attributeEqualTo' => true, + 'callback' => true, + 'classHasAttribute' => true, + 'classHasStaticAttribute' => true, + 'contains' => true, + 'containsEqual' => true, + 'containsIdentical' => true, + 'containsOnly' => true, + 'containsOnlyArray' => true, + 'containsOnlyBool' => true, + 'containsOnlyCallable' => true, + 'containsOnlyClosedResource' => true, + 'containsOnlyFloat' => true, + 'containsOnlyInstancesOf' => true, + 'containsOnlyInt' => true, + 'containsOnlyIterable' => true, + 'containsOnlyNull' => true, + 'containsOnlyNumeric' => true, + 'containsOnlyObject' => true, + 'containsOnlyResource' => true, + 'containsOnlyScalar' => true, + 'containsOnlyString' => true, + 'countOf' => true, + 'directoryExists' => true, + 'equalTo' => true, + 'equalToCanonicalizing' => true, + 'equalToIgnoringCase' => true, + 'equalToWithDelta' => true, + 'fail' => true, + 'fileExists' => true, + 'getCount' => true, + 'getObjectAttribute' => true, + 'getStaticAttribute' => true, + 'greaterThan' => true, + 'greaterThanOrEqual' => true, + 'identicalTo' => true, + 'isArray' => true, + 'isBool' => true, + 'isCallable' => true, + 'isClosedResource' => true, + 'isEmpty' => true, + 'isFalse' => true, + 'isFinite' => true, + 'isFloat' => true, + 'isInfinite' => true, + 'isInstanceOf' => true, + 'isInt' => true, + 'isIterable' => true, + 'isJson' => true, + 'isList' => true, + 'isNan' => true, + 'isNull' => true, + 'isNumeric' => true, + 'isObject' => true, + 'isReadable' => true, + 'isResource' => true, + 'isScalar' => true, + 'isString' => true, + 'isTrue' => true, + 'isType' => true, + 'isWritable' => true, + 'lessThan' => true, + 'lessThanOrEqual' => true, + 'logicalAnd' => true, + 'logicalNot' => true, + 'logicalOr' => true, + 'logicalXor' => true, + 'markTestIncomplete' => true, + 'markTestSkipped' => true, + 'matches' => true, + 'matchesRegularExpression' => true, + 'objectEquals' => true, + 'objectHasAttribute' => true, + 'readAttribute' => true, + 'resetCount' => true, + 'stringContains' => true, + 'stringEndsWith' => true, + 'stringEqualsStringIgnoringLineEndings' => true, + 'stringEqualsStringIgnoringWhitespace' => true, + 'stringStartsWith' => true, + + // TestCase methods + 'any' => true, + 'at' => true, + 'atLeast' => true, + 'atLeastOnce' => true, + 'atMost' => true, + 'createStub' => true, + 'createConfiguredStub' => true, + 'createStubForIntersectionOfInterfaces' => true, + 'exactly' => true, + 'getStubBuilder' => true, + 'never' => true, + 'once' => true, + 'onConsecutiveCalls' => true, + 'returnArgument' => true, + 'returnCallback' => true, + 'returnSelf' => true, + 'returnValue' => true, + 'returnValueMap' => true, + 'setUpBeforeClass' => true, + 'tearDownAfterClass' => true, + 'throwException' => true, + ]; + + /** + * @var array + */ + private const ALLOWED_VALUES = [ + self::CALL_TYPE_THIS => true, + self::CALL_TYPE_SELF => true, + self::CALL_TYPE_STATIC => true, + ]; + + /** + * @var non-empty-array + */ + private array $conversionMap = [ + self::CALL_TYPE_THIS => [[\T_OBJECT_OPERATOR, '->'], [\T_VARIABLE, '$this']], + self::CALL_TYPE_SELF => [[\T_DOUBLE_COLON, '::'], [\T_STRING, 'self']], + self::CALL_TYPE_STATIC => [[\T_DOUBLE_COLON, '::'], [\T_STATIC, 'static']], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'PHP' + assertSame(1, 2); + self::assertSame(1, 2); + static::assertSame(1, 2); + static::assertTrue(false); + } + } + + PHP; + + return new FixerDefinition( + 'Calls to `PHPUnit\Framework\TestCase` static methods (like assertions) must all be of the same type, either `$this->`, `self::` or `static::`.', + [ + new CodeSample($codeSample), + new CodeSample($codeSample, ['call_type' => self::CALL_TYPE_THIS]), + new CodeSample($codeSample, ['methods' => ['assertTrue' => self::CALL_TYPE_THIS]]), + ], + null, + 'Risky when PHPUnit methods are overridden or not accessible, or when project has PHPUnit incompatibilities.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before SelfStaticAccessorFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('call_type', 'The call type to use for referring to PHPUnit methods.')) + ->setAllowedTypes(['string']) + ->setAllowedValues(array_keys(self::ALLOWED_VALUES)) + ->setDefault(Future::getV4OrV3(self::CALL_TYPE_THIS, self::CALL_TYPE_STATIC)) // vide https://github.com/sebastianbergmann/phpunit/issues/2104#issuecomment-192919598 + ->getOption(), + (new FixerOptionBuilder('methods', 'Dictionary of `method` => `call_type` values that differ from the default strategy.')) + ->setAllowedTypes(['array']) + ->setAllowedValues([static function (array $option): bool { + foreach ($option as $method => $value) { + if (!isset(self::METHODS[$method])) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected "methods" key, expected any of %s, got "%s".', + Utils::naturalLanguageJoin(array_keys(self::METHODS)), + \gettype($method).'#'.$method, + ), + ); + } + + if (!isset(self::ALLOWED_VALUES[$value])) { + throw new InvalidOptionsException( + \sprintf( + 'Unexpected value for method "%s", expected any of %s, got "%s".', + $method, + Utils::naturalLanguageJoin(array_keys(self::ALLOWED_VALUES)), + \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value), + ), + ); + } + } + + return true; + }]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('target', 'Target version of PHPUnit.')) + ->setAllowedTypes(['string']) + ->setAllowedValues([ + PhpUnitTargetVersion::VERSION_10_0, + PhpUnitTargetVersion::VERSION_11_0, + PhpUnitTargetVersion::VERSION_NEWEST, + ]) + ->setDefault(Future::getV4OrV3(PhpUnitTargetVersion::VERSION_NEWEST, PhpUnitTargetVersion::VERSION_10_0)) + ->getOption(), + ]); + } + + protected function configurePostNormalisation(): void + { + $dynamicMethods = []; + if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_11_0)) { + // not statc since v11 + $dynamicMethods = [ + 'any', + 'atLeast', + 'atLeastOnce', + 'atMost', + 'exactly', + 'never', + 'once', + 'throwException', + ]; + } + if (PhpUnitTargetVersion::VERSION_11_0 === $this->configuration['target']) { + // not static since v11, removed in v12 + $dynamicMethods[] = 'onConsecutiveCalls'; + $dynamicMethods[] = 'returnArgument'; + $dynamicMethods[] = 'returnCallback'; + $dynamicMethods[] = 'returnSelf'; + $dynamicMethods[] = 'returnValue'; + $dynamicMethods[] = 'returnValueMap'; + } + + foreach ($dynamicMethods as $method) { + if (isset($this->configuration['methods'][$method])) { + throw new InvalidFixerConfigurationException( + $this->getName(), + \sprintf('Configuration cannot contain method "%s" and target "%s", it is dynamic in that PHPUnit version.', $method, $this->configuration['target']), + ); + } + + $this->configuration['methods'][$method] = self::CALL_TYPE_THIS; + } + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $startIndex; $index < $endIndex; ++$index) { + // skip anonymous classes + if ($tokens[$index]->isGivenKind(\T_CLASS)) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + + $callType = $this->configuration['call_type']; + + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + // skip lambda + if ($analyzer->isLambda($index)) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + + // do not change `self` to `this` in static methods + if (self::CALL_TYPE_THIS === $callType) { + $attributes = $analyzer->getMethodAttributes($index); + + if (false !== $attributes['static']) { + $index = $this->findEndOfNextBlock($tokens, $index); + + continue; + } + } + } + + if (!$tokens[$index]->isGivenKind(\T_STRING) || !isset(self::METHODS[$tokens[$index]->getContent()])) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$nextIndex]->equals('(')) { + $index = $nextIndex; + + continue; + } + + if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + continue; + } + + $methodName = $tokens[$index]->getContent(); + + if (isset($this->configuration['methods'][$methodName])) { + $callType = $this->configuration['methods'][$methodName]; + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($index); + $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); + + if (!$this->needsConversion($tokens, $index, $referenceIndex, $callType)) { + continue; + } + + \assert(isset($this->conversionMap[$callType])); // for PHPStan + $tokens[$operatorIndex] = new Token($this->conversionMap[$callType][0]); + $tokens[$referenceIndex] = new Token($this->conversionMap[$callType][1]); + } + } + + private function needsConversion(Tokens $tokens, int $index, int $referenceIndex, string $callType): bool + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + \assert(isset($this->conversionMap[$callType])); // for PHPStan + + return $functionsAnalyzer->isTheSameClassCall($tokens, $index) + && !$tokens[$referenceIndex]->equals($this->conversionMap[$callType][1], false); + } + + private function findEndOfNextBlock(Tokens $tokens, int $index): int + { + $nextIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + + return $tokens[$nextIndex]->equals('{') + ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $nextIndex) + : $nextIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php new file mode 100644 index 0000000..d87c302 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitTestClassRequiresCoversFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Adds a default `@coversNothing` annotation to PHPUnit test classes that have no `@covers*` annotation.', + [ + new CodeSample( + <<<'PHP' + assertSame(a(), b()); + } + } + + PHP, + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpUnitAttributesFixer, PhpdocSeparationFixer. + */ + public function getPriority(): int + { + return 9; + } + + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + + $tokensAnalyzer = new TokensAnalyzer($tokens); + + if ($tokensAnalyzer->isAnonymousClass($classIndex)) { + return; + } + + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + + if (isset($modifiers['abstract'])) { + return; // don't add `@covers` annotation for abstract base classes + } + + $this->ensureIsDocBlockWithAnnotation( + $tokens, + $classIndex, + 'coversNothing', + [ + 'covers', + 'coversDefaultClass', + 'coversNothing', + ], + [ + 'phpunit\framework\attributes\coversclass', + 'phpunit\framework\attributes\coversnothing', + 'phpunit\framework\attributes\coversmethod', + 'phpunit\framework\attributes\coversfunction', + 'phpunit\framework\attributes\coverstrait', + ], + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php new file mode 100644 index 0000000..494269e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php @@ -0,0 +1,186 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * comment_type?: 'all_multiline'|'phpdocs_like'|'phpdocs_only', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * comment_type: 'all_multiline'|'phpdocs_like'|'phpdocs_only', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * @author Julien Falque + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AlignMultilineCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var null|non-empty-list + */ + private ?array $tokenKinds = null; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one.', + [ + new CodeSample( + <<<'PHP' + 'phpdocs_like'], + ), + new CodeSample( + <<<'PHP' + 'all_multiline'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after ArrayIndentationFixer. + */ + public function getPriority(): int + { + return 27; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->tokenKinds); + } + + protected function configurePostNormalisation(): void + { + $this->tokenKinds = [\T_DOC_COMMENT]; + if ('phpdocs_only' !== $this->configuration['comment_type']) { + $this->tokenKinds[] = \T_COMMENT; + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind($this->tokenKinds)) { + continue; + } + + $whitespace = ''; + $previousIndex = $index - 1; + + if ($tokens[$previousIndex]->isWhitespace()) { + $whitespace = $tokens[$previousIndex]->getContent(); + --$previousIndex; + } + + if ($tokens[$previousIndex]->isGivenKind(\T_OPEN_TAG)) { + $whitespace = Preg::replace('/\S/', '', $tokens[$previousIndex]->getContent()).$whitespace; + } + + if (!Preg::match('/\R(\h*)$/', $whitespace, $matches)) { + continue; + } + + if ($token->isGivenKind(\T_COMMENT) && 'all_multiline' !== $this->configuration['comment_type'] && Preg::match('/\R(?:\R|\s*[^\s\*])/', $token->getContent())) { + continue; + } + + $indentation = $matches[1]; + $lines = Preg::split('/\R/u', $token->getContent()); + + foreach ($lines as $lineNumber => $line) { + if (0 === $lineNumber) { + continue; + } + + $line = ltrim($line); + + if ($token->isGivenKind(\T_COMMENT) && (!isset($line[0]) || '*' !== $line[0])) { + continue; + } + + if (!isset($line[0])) { + $line = '*'; + } elseif ('*' !== $line[0]) { + $line = '* '.$line; + } + + $lines[$lineNumber] = $indentation.' '.$line; + } + + $tokens[$index] = new Token([$token->getId(), implode($lineEnding, $lines)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('comment_type', 'Whether to fix PHPDoc comments only (`phpdocs_only`), any multi-line comment whose lines all start with an asterisk (`phpdocs_like`) or any multi-line comment (`all_multiline`).')) + ->setAllowedValues(['phpdocs_only', 'phpdocs_like', 'all_multiline']) + ->setDefault('phpdocs_only') + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php new file mode 100644 index 0000000..1b655cb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php @@ -0,0 +1,185 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * annotations?: list, + * case_sensitive?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * annotations: list, + * case_sensitive: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GeneralPhpdocAnnotationRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes configured annotations from PHPDoc.', + [ + new CodeSample( + <<<'PHP' + ['author']], + ), + new CodeSample( + <<<'PHP' + ['author'], 'case_sensitive' => false], + ), + new CodeSample( + <<<'PHP' + ['package', 'subpackage']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocLineSpanFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['annotations'])) { + return; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $this->getAnnotationsToRemove($doc); + + // nothing to do if there are no annotations + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $annotation->remove(); + } + + if ('' === $doc->getContent()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } else { + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotations', 'List of annotations to remove, e.g. `["author"]`.')) + ->setAllowedTypes(['string[]']) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Should annotations be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * @return list + */ + private function getAnnotationsToRemove(DocBlock $doc): array + { + if (true === $this->configuration['case_sensitive']) { + return $doc->getAnnotationsOfType($this->configuration['annotations']); + } + + $typesToSearchFor = array_map(static fn (string $type): string => strtolower($type), $this->configuration['annotations']); + + $annotations = []; + + foreach ($doc->getAnnotations() as $annotation) { + $tagName = strtolower($annotation->getTag()->getName()); + if (\in_array($tagName, $typesToSearchFor, true)) { + $annotations[] = $annotation; + } + } + + return $annotations; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php new file mode 100644 index 0000000..7bbb237 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php @@ -0,0 +1,217 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * fix_annotation?: bool, + * fix_inline?: bool, + * replacements?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * fix_annotation: bool, + * fix_inline: bool, + * replacements: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GeneralPhpdocTagRenameFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Renames PHPDoc tags.', + [ + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'fix_annotation' => false, + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'fix_inline' => false, + ]), + new CodeSample(" [ + 'inheritDocs' => 'inheritDoc', + ], + 'case_sensitive' => true, + ]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + // must be run before PhpdocAddMissingParamAnnotationFixer + return 11; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('fix_annotation', 'Whether annotation tags should be fixed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('fix_inline', 'Whether inline tags should be fixed.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('replacements', 'A map of tags to replace.')) + ->setAllowedTypes(['array']) + ->setNormalizer(static function (Options $options, array $value): array { + $normalizedValue = []; + + foreach ($value as $from => $to) { + if (!\is_string($from)) { + throw new InvalidOptionsException('Tag to replace must be a string.'); + } + + if (!Preg::match('#^\S+$#', $to) || str_contains($to, '*/')) { + throw new InvalidOptionsException(\sprintf( + 'Tag "%s" cannot be replaced by invalid tag "%s".', + $from, + $to, + )); + } + + $from = trim($from); + $to = trim($to); + + if (false === $options['case_sensitive']) { + $lowercaseFrom = strtolower($from); + + if (isset($normalizedValue[$lowercaseFrom]) && $normalizedValue[$lowercaseFrom] !== $to) { + throw new InvalidOptionsException(\sprintf( + 'Tag "%s" cannot be configured to be replaced with several different tags when case sensitivity is off.', + $from, + )); + } + + $from = $lowercaseFrom; + } + + $normalizedValue[$from] = $to; + } + + foreach ($normalizedValue as $from => $to) { + if (isset($normalizedValue[$to]) && $normalizedValue[$to] !== $to) { + throw new InvalidOptionsException(\sprintf( + 'Cannot change tag "%1$s" to tag "%2$s", as the tag "%2$s" is configured to be replaced to "%3$s".', + $from, + $to, + $normalizedValue[$to], + )); + } + } + + return $normalizedValue; + }) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether tags should be replaced only if they have exact same casing.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['replacements'])) { + return; + } + + if (true === $this->configuration['fix_annotation']) { + $regex = true === $this->configuration['fix_inline'] + ? '/(["\'])[^\1]*\1(*SKIP)(*FAIL)|\b(?<=@)(?P%s)\b/' + : '/(["\'])[^\1]*\1(*SKIP)(*FAIL)|(?%s)(?!\})/'; + } else { + $regex = '/(?<={@)(?P%s)(?=[ \t}])/'; + } + + $caseInsensitive = false === $this->configuration['case_sensitive']; + $replacements = $this->configuration['replacements']; + $regex = \sprintf($regex, implode('|', array_keys($replacements))); + + if ($caseInsensitive) { + $regex .= 'i'; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replaceCallback( + $regex, + static function (array $matches) use ($caseInsensitive, $replacements) { + \assert(isset($matches['tag'])); + if ($caseInsensitive) { + $matches['tag'] = strtolower($matches['tag']); + } + + \assert(isset($replacements[$matches['tag']])); + + return $replacements[$matches['tag']]; + }, + $token->getContent(), + )]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php new file mode 100644 index 0000000..b2beb23 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoBlankLinesAfterPhpdocFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be blank lines between docblock and the documented element.', + [ + new CodeSample( + <<<'PHP' + $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + // get the next non-whitespace token inc comments, provided + // that there is whitespace between it and the current token + $next = $tokens->getNextNonWhitespace($index); + if ($index + 2 === $next && false === $tokens[$next]->isGivenKind([ + \T_BREAK, + \T_COMMENT, + \T_CONTINUE, + \T_DECLARE, + \T_DOC_COMMENT, + \T_GOTO, + \T_INCLUDE, + \T_INCLUDE_ONCE, + \T_NAMESPACE, + \T_REQUIRE, + \T_REQUIRE_ONCE, + \T_RETURN, + \T_THROW, + \T_USE, + \T_WHITESPACE, + ])) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + \assert(false !== strrpos($content, "\n")); + $tokens[$index] = new Token([\T_WHITESPACE, substr($content, strrpos($content, "\n"))]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php new file mode 100644 index 0000000..ff8f823 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoEmptyPhpdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be empty PHPDoc blocks.', + [new CodeSample("isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + if (!Preg::match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) { + continue; + } + + if ( + $tokens[$index - 1]->isGivenKind([\T_OPEN_TAG, \T_WHITESPACE]) + && substr_count($tokens[$index - 1]->getContent(), "\n") > 0 + && $tokens[$index + 1]->isGivenKind(\T_WHITESPACE) + && Preg::match('/^\R/', $tokens[$index + 1]->getContent()) + ) { + $tokens[$index - 1] = new Token([ + $tokens[$index - 1]->getId(), + Preg::replace('/\h*$/', '', $tokens[$index - 1]->getContent()), + ]); + + $newContent = Preg::replace('/^\R/', '', $tokens[$index + 1]->getContent()); + if ('' === $newContent) { + $tokens->clearAt($index + 1); + } else { + $tokens[$index + 1] = new Token([\T_WHITESPACE, $newContent]); + } + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php new file mode 100644 index 0000000..2be5eed --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php @@ -0,0 +1,763 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _TypeInfo array{ + * types: list, + * allows_null: bool, + * } + * @phpstan-type _DocumentElement array{ + * index: int, + * type: 'classy'|'function'|'property', + * modifiers: array, + * types: array, + * } + * @phpstan-type _AutogeneratedInputConfiguration array{ + * allow_hidden_params?: bool, + * allow_mixed?: bool, + * allow_unused_params?: bool, + * remove_inheritdoc?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * allow_hidden_params: bool, + * allow_mixed: bool, + * allow_unused_params: bool, + * remove_inheritdoc: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSuperfluousPhpdocTagsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @var _TypeInfo */ + private const NO_TYPE_INFO = [ + 'types' => [], + 'allows_null' => true, + ]; + private const SYMBOL_KINDS = [\T_CLASS, \T_INTERFACE, FCT::T_ENUM]; + + private const MODIFIER_KINDS = [ + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_ABSTRACT, + \T_FINAL, + \T_STATIC, + FCT::T_READONLY, + FCT::T_PRIVATE_SET, + FCT::T_PROTECTED_SET, + FCT::T_PUBLIC_SET, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes `@param`, `@return` and `@var` tags that don\'t provide any useful information.', + [ + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocLineSpanFixer, VoidReturnFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, FullyQualifiedStrictTypesFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 6; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $namespaceUseAnalyzer = new NamespaceUsesAnalyzer(); + $shortNames = []; + $currentSymbol = null; + $currentSymbolEndIndex = null; + + foreach ($namespaceUseAnalyzer->getDeclarationsFromTokens($tokens) as $namespaceUseAnalysis) { + $shortNames[strtolower($namespaceUseAnalysis->getShortName())] = strtolower($namespaceUseAnalysis->getFullName()); + } + + foreach ($tokens as $index => $token) { + if ($index === $currentSymbolEndIndex) { + $currentSymbol = null; + $currentSymbolEndIndex = null; + + continue; + } + + if ($token->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + + if ($token->isGivenKind(self::SYMBOL_KINDS)) { + $currentSymbol = $tokens[$tokens->getNextMeaningfulToken($index)]->getContent(); + $currentSymbolEndIndex = $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_BRACE, + $tokens->getNextTokenOfKind($index, ['{']), + ); + + continue; + } + + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $documentedElement = $this->findDocumentedElement($tokens, $index); + + if (null === $documentedElement) { + continue; + } + + $content = $initialContent = $token->getContent(); + + if (true === $this->configuration['remove_inheritdoc']) { + $content = $this->removeSuperfluousInheritDoc($content); + } + + $namespace = (new NamespacesAnalyzer())->getNamespaceAt($tokens, $index)->getFullName(); + if ('' === $namespace) { + $namespace = null; + } + + if ('function' === $documentedElement['type']) { + $content = $this->fixFunctionDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); + } elseif ('property' === $documentedElement['type']) { + $content = $this->fixPropertyDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); + } elseif ('classy' === $documentedElement['type']) { + $content = $this->fixClassDocComment($content, $documentedElement); + } else { + throw new \RuntimeException('Unknown type.'); + } + + if ('' === $content) { + $content = '/** */'; + } + + if ($content !== $initialContent) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('allow_mixed', 'Whether type `mixed` without description is allowed (`true`) or considered superfluous (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('remove_inheritdoc', 'Remove `@inheritDoc` tags.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('allow_hidden_params', 'Whether `param` annotation for hidden params in method signature are allowed.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + (new FixerOptionBuilder('allow_unused_params', 'Whether `param` annotation without actual signature is allowed (`true`) or considered superfluous (`false`).')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + /** + * @return null|_DocumentElement + */ + private function findDocumentedElement(Tokens $tokens, int $docCommentIndex): ?array + { + $typeKinds = [ + CT::T_NULLABLE_TYPE, + CT::T_ARRAY_TYPEHINT, + CT::T_TYPE_ALTERNATION, + CT::T_TYPE_INTERSECTION, + \T_STRING, + \T_NS_SEPARATOR, + ]; + + $element = [ + 'modifiers' => [], + 'types' => [], + ]; + + $index = $tokens->getNextMeaningfulToken($docCommentIndex); + + if (null !== $index && $tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { + do { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $tokens->getNextMeaningfulToken($index); + } while (null !== $index && $tokens[$index]->isGivenKind(\T_ATTRIBUTE)); + } + + while (true) { + if (null === $index) { + break; + } + + if ($tokens[$index]->isClassy()) { + $element['index'] = $index; + $element['type'] = 'classy'; + + return $element; + } + + if ($tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { + $element['index'] = $index; + $element['type'] = 'function'; + + return $element; + } + + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + $element['index'] = $index; + $element['type'] = 'property'; + + return $element; + } + + if ($tokens[$index]->isGivenKind(self::MODIFIER_KINDS)) { + $element['modifiers'][$index] = $tokens[$index]; + } elseif ($tokens[$index]->isGivenKind($typeKinds)) { + $element['types'][$index] = $tokens[$index]; + } else { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return null; + } + + /** + * @param _DocumentElement&array{type: 'function', ...} $element + * @param null|non-empty-string $namespace + * @param array $shortNames + */ + private function fixFunctionDocComment( + string $content, + Tokens $tokens, + array $element, + ?string $namespace, + ?string $currentSymbol, + array $shortNames + ): string { + $docBlock = new DocBlock($content); + + $openingParenthesisIndex = $tokens->getNextTokenOfKind($element['index'], ['(']); + $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openingParenthesisIndex); + + $argumentsInfo = $this->getArgumentsInfo( + $tokens, + $openingParenthesisIndex + 1, + $closingParenthesisIndex - 1, + ); + + foreach ($docBlock->getAnnotationsOfType('param') as $annotation) { + $argumentName = $annotation->getVariableName(); + + if (null === $argumentName) { + if ($this->annotationIsSuperfluous($annotation, self::NO_TYPE_INFO, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + + continue; + } + + if (!isset($argumentsInfo[$argumentName]) && true === $this->configuration['allow_unused_params']) { + continue; + } + + if (!isset($argumentsInfo[$argumentName]) || $this->annotationIsSuperfluous($annotation, $argumentsInfo[$argumentName], $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + $returnTypeInfo = $this->getReturnTypeInfo($tokens, $closingParenthesisIndex); + + foreach ($docBlock->getAnnotationsOfType('return') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $returnTypeInfo, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + + return $docBlock->getContent(); + } + + /** + * @param _DocumentElement&array{type: 'property', ...} $element + * @param null|non-empty-string $namespace + * @param array $shortNames + */ + private function fixPropertyDocComment( + string $content, + Tokens $tokens, + array $element, + ?string $namespace, + ?string $currentSymbol, + array $shortNames + ): string { + if (\count($element['types']) > 0) { + $propertyTypeInfo = $this->parseTypeHint($tokens, array_key_first($element['types'])); + } else { + $propertyTypeInfo = self::NO_TYPE_INFO; + } + + $docBlock = new DocBlock($content); + + foreach ($docBlock->getAnnotationsOfType('var') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $propertyTypeInfo, $namespace, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + + return $docBlock->getContent(); + } + + /** + * @param _DocumentElement&array{type: 'classy', ...} $element + */ + private function fixClassDocComment(string $content, array $element): string + { + $docBlock = new DocBlock($content); + + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + + return $docBlock->getContent(); + } + + /** + * @return array + */ + private function getArgumentsInfo(Tokens $tokens, int $start, int $end): array + { + $argumentsInfo = []; + + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_VARIABLE)) { + continue; + } + + $beforeArgumentIndex = $tokens->getPrevTokenOfKind($index, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + $typeIndex = $tokens->getNextMeaningfulToken($beforeArgumentIndex); + + if ($typeIndex !== $index) { + $info = $this->parseTypeHint($tokens, $typeIndex); + } else { + $info = self::NO_TYPE_INFO; + } + + if (!$info['allows_null']) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ( + $tokens[$nextIndex]->equals('=') + && $tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals([\T_STRING, 'null'], false) + ) { + $info['allows_null'] = true; + } + } + + $argumentsInfo[$token->getContent()] = $info; + } + + // virtualise "hidden params" as if they would be regular ones + if (true === $this->configuration['allow_hidden_params']) { + $paramsString = $tokens->generatePartialCode($start, $end); + Preg::matchAll('|/\*[^$]*(\$\w+)[^*]*\*/|', $paramsString, $matches); + + foreach ($matches[1] as $match) { + $argumentsInfo[$match] = self::NO_TYPE_INFO; // HINT: one could try to extract actual type for hidden param, for now we only indicate it's existence + } + } + + return $argumentsInfo; + } + + /** + * @return _TypeInfo + */ + private function getReturnTypeInfo(Tokens $tokens, int $closingParenthesisIndex): array + { + $colonIndex = $tokens->getNextMeaningfulToken($closingParenthesisIndex); + + return $tokens[$colonIndex]->isGivenKind(CT::T_TYPE_COLON) + ? $this->parseTypeHint($tokens, $tokens->getNextMeaningfulToken($colonIndex)) + : self::NO_TYPE_INFO; + } + + /** + * @param int $index The index of the first token of the type hint + * + * @return _TypeInfo + */ + private function parseTypeHint(Tokens $tokens, int $index): array + { + $allowsNull = false; + + $types = []; + + while (true) { + $type = ''; + + if ($tokens[$index]->isGivenKind([FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET])) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE])) { + $index = $tokens->getNextMeaningfulToken($index); + + continue; + } + + if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $allowsNull = true; + $index = $tokens->getNextMeaningfulToken($index); + } + + while ($tokens[$index]->isGivenKind([\T_NS_SEPARATOR, \T_STATIC, \T_STRING, CT::T_ARRAY_TYPEHINT, \T_CALLABLE])) { + $type .= $tokens[$index]->getContent(); + $index = $tokens->getNextMeaningfulToken($index); + } + + if ('' === $type) { + break; + } + + $types[] = $type; + + if (!$tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return [ + 'types' => $types, + 'allows_null' => $allowsNull, + ]; + } + + /** + * @param _TypeInfo $info + * @param null|non-empty-string $namespace + * @param array $symbolShortNames + */ + private function annotationIsSuperfluous( + Annotation $annotation, + array $info, + ?string $namespace, + ?string $currentSymbol, + array $symbolShortNames + ): bool { + if ('param' === $annotation->getTag()->getName()) { + $regex = '{\*\h*@param(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\h+(?:\&\h*)?(?:\.{3}\h*)?\$\S+)?(?:\s+(?(?!\*+\/)\S+))?}s'; + } elseif ('var' === $annotation->getTag()->getName()) { + $regex = '{\*\h*@var(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\h+\$\S+)?(?:\s+(?(?!\*\/)\S+))?}s'; + } else { + $regex = '{\*\h*@return(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\s+(?(?!\*\/)\S+))?}s'; + } + + if (!Preg::match($regex, $annotation->getContent(), $matches)) { + // Unable to match the annotation, it must be malformed or has unsupported format. + // Either way we don't want to tinker with it. + return false; + } + + if (isset($matches['description'])) { + return false; + } + + if (!isset($matches['types']) || '' === $matches['types']) { + // If there's no type info in the annotation, further checks make no sense, exit early. + return true; + } + + $annotationTypes = $this->toComparableNames($annotation->getTypes(), $namespace, $currentSymbol, $symbolShortNames); + + if (['null'] === $annotationTypes && ['null'] !== $info['types']) { + return false; + } + + if (['mixed'] === $annotationTypes && [] === $info['types']) { + return false === $this->configuration['allow_mixed']; + } + + $actualTypes = $info['types']; + + if ($info['allows_null']) { + $actualTypes[] = 'null'; + } + + $actualTypes = $this->toComparableNames($actualTypes, $namespace, $currentSymbol, $symbolShortNames); + + if ($annotationTypes === $actualTypes) { + return true; + } + + // retry comparison with annotation type unioned with null + // phpstan implies the null presence from the native type + $annotationTypes = array_merge($annotationTypes, ['null']); + sort($annotationTypes); + + return $actualTypes === $annotationTypes; + } + + /** + * Normalizes types to make them comparable. + * + * Converts given types to lowercase, replaces imports aliases with + * their matching FQCN, and finally sorts the result. + * + * @param list $types The types to normalize + * @param null|non-empty-string $namespace + * @param array $symbolShortNames The imports aliases + * + * @return list The normalized types + */ + private function toComparableNames(array $types, ?string $namespace, ?string $currentSymbol, array $symbolShortNames): array + { + if (isset($types[0][0]) && '?' === $types[0][0]) { + $types = [ + substr($types[0], 1), + 'null', + ]; + } + + $normalized = array_map( + function (string $type) use ($namespace, $currentSymbol, $symbolShortNames): string { + if (str_contains($type, '&')) { + $intersects = explode('&', $type); + + $intersects = $this->toComparableNames($intersects, $namespace, $currentSymbol, $symbolShortNames); + + return implode('&', $intersects); + } + + if ('self' === $type && null !== $currentSymbol) { + $type = $currentSymbol; + } + + $type = strtolower($type); + + if (isset($symbolShortNames[$type])) { + return $symbolShortNames[$type]; // always FQCN /wo leading backslash and in lower-case + } + + if (str_starts_with($type, '\\')) { + return substr($type, 1); + } + + if (null !== $namespace && !(new TypeAnalysis($type))->isReservedType()) { + $type = strtolower($namespace).'\\'.$type; + } + + return $type; + }, + $types, + ); + + sort($normalized); + + return $normalized; + } + + private function removeSuperfluousInheritDoc(string $docComment): string + { + return Preg::replace('~ + # $1: before @inheritDoc tag + ( + # beginning of comment or a PHPDoc tag + (?: + ^/\*\* + (?: + \R + [ \t]*(?:\*[ \t]*)? + )*? + | + @\N+ + ) + + # empty comment lines + (?: + \R + [ \t]*(?:\*[ \t]*?)? + )* + ) + + # spaces before @inheritDoc tag + [ \t]* + + # @inheritDoc tag + (?:@inheritDocs?|\{@inheritDocs?\}) + + # $2: after @inheritDoc tag + ( + # empty comment lines + (?: + \R + [ \t]*(?:\*[ \t]*)? + )* + + # a PHPDoc tag or end of comment + (?: + @\N+ + | + (?: + \R + [ \t]*(?:\*[ \t]*)? + )* + [ \t]*\*/$ + ) + ) + ~ix', '$1$2', $docComment); + } + + /** + * @param _DocumentElement $element + */ + private function removeSuperfluousModifierAnnotation(DocBlock $docBlock, array $element): void + { + foreach (['abstract' => \T_ABSTRACT, 'final' => \T_FINAL] as $annotationType => $modifierToken) { + $annotations = $docBlock->getAnnotationsOfType($annotationType); + + foreach ($element['modifiers'] as $token) { + if ($token->isGivenKind($modifierToken)) { + foreach ($annotations as $annotation) { + $annotation->remove(); + } + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php new file mode 100644 index 0000000..347274e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php @@ -0,0 +1,309 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * only_untyped?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * only_untyped: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocAddMissingParamAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc should contain `@param` for all params.', + [ + new CodeSample( + <<<'PHP' + true], + ), + new CodeSample( + <<<'PHP' + false], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, PhpdocOrderFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocTagRenameFixer, PhpdocIndentFixer, PhpdocNoAliasTagFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $tokenContent = $token->getContent(); + + if (str_contains(strtolower($tokenContent), strtolower('inheritdoc'))) { + continue; + } + + // ignore one-line phpdocs like `/** foo */`, as there is no place to put new annotations + if (!str_contains($tokenContent, "\n")) { + continue; + } + + $mainIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + if (null === $index) { + return; + } + + while ($tokens[$index]->isGivenKind([ + \T_ABSTRACT, + \T_FINAL, + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_STATIC, + ])) { + $index = $tokens->getNextMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openIndex); + + $arguments = []; + + foreach ($argumentsAnalyzer->getArguments($tokens, $openIndex, $index) as $start => $end) { + $argumentInfo = $this->prepareArgumentInformation($tokens, $start, $end); + + if (false === $this->configuration['only_untyped'] || '' === $argumentInfo['type']) { + $arguments[$argumentInfo['name']] = $argumentInfo; + } + } + + if (0 === \count($arguments)) { + continue; + } + + $doc = new DocBlock($tokenContent); + $lastParamLine = null; + + foreach ($doc->getAnnotationsOfType('param') as $annotation) { + $pregMatched = Preg::match('/^[^$]+(\$\w+).*$/s', $annotation->getContent(), $matches); + + if ($pregMatched) { + unset($arguments[$matches[1]]); + } + + $lastParamLine = max($lastParamLine, $annotation->getEnd()); + } + + if (0 === \count($arguments)) { + continue; + } + + $lines = $doc->getLines(); + $linesCount = \count($lines); + + \assert(isset($lines[$linesCount - 1])); + Preg::match('/^(\s*).*$/', $lines[$linesCount - 1]->getContent(), $matches); + \assert(isset($matches[1])); + $indent = $matches[1]; + + $newLines = []; + + foreach ($arguments as $argument) { + $type = '' !== $argument['type'] ? $argument['type'] : 'mixed'; + + if (!str_starts_with($type, '?') && 'null' === strtolower($argument['default'])) { + $type = 'null|'.$type; + } + + $newLines[] = new Line(\sprintf( + '%s* @param %s %s%s', + $indent, + $type, + $argument['name'], + $this->whitespacesConfig->getLineEnding(), + )); + } + + array_splice( + $lines, + $lastParamLine > 0 ? $lastParamLine + 1 : $linesCount - 1, + 0, + $newLines, + ); + + $tokens[$mainIndex] = new Token([\T_DOC_COMMENT, implode('', $lines)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('only_untyped', 'Whether to add missing `@param` annotations for untyped parameters only.')) + ->setDefault(true) + ->setAllowedTypes(['bool']) + ->getOption(), + ]); + } + + /** + * @return array{default: string, name: string, type: string} + */ + private function prepareArgumentInformation(Tokens $tokens, int $start, int $end): array + { + $info = [ + 'default' => '', + 'name' => '', + 'type' => '', + ]; + + $sawName = false; + + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ( + $token->isComment() + || $token->isWhitespace() + || $token->isGivenKind([ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + FCT::T_READONLY, + FCT::T_PRIVATE_SET, + FCT::T_PROTECTED_SET, + FCT::T_PUBLIC_SET, + ]) + ) { + continue; + } + + if ($token->isGivenKind(\T_VARIABLE)) { + $sawName = true; + $info['name'] = $token->getContent(); + + continue; + } + + if ($token->equals('=')) { + continue; + } + + if ($sawName) { + $info['default'] .= $token->getContent(); + } elseif (!$token->equals('&')) { + if ($token->isGivenKind(\T_ELLIPSIS)) { + if ('' === $info['type']) { + $info['type'] = 'array'; + } else { + $info['type'] .= '[]'; + } + } else { + $info['type'] .= $token->getContent(); + } + } + } + + return $info; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php new file mode 100644 index 0000000..59af3b8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php @@ -0,0 +1,513 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * align?: 'left'|'vertical', + * spacing?: array|int, + * tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * align: 'left'|'vertical', + * spacing: array|int, + * tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Sebastiaan Stok + * @author Graham Campbell + * @author Dariusz Rumiński + * @author Jakub Kwaśniewski + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocAlignFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const ALIGN_LEFT = 'left'; + + /** + * @internal + */ + public const ALIGN_VERTICAL = 'vertical'; + + private const DEFAULT_TAGS = [ + 'method', + 'param', + 'property', + 'return', + 'throws', + 'type', + 'var', + ]; + + private const TAGS_WITH_NAME = [ + 'param', + 'property', + 'property-read', + 'property-write', + 'phpstan-param', + 'phpstan-property', + 'phpstan-property-read', + 'phpstan-property-write', + 'phpstan-assert', + 'phpstan-assert-if-true', + 'phpstan-assert-if-false', + 'psalm-param', + 'psalm-param-out', + 'psalm-property', + 'psalm-property-read', + 'psalm-property-write', + 'psalm-assert', + 'psalm-assert-if-true', + 'psalm-assert-if-false', + ]; + + private const TAGS_WITH_METHOD_SIGNATURE = [ + 'method', + 'phpstan-method', + 'psalm-method', + ]; + + private const DEFAULT_SPACING = 1; + + private const DEFAULT_SPACING_KEY = '_default'; + + private string $regex; + + private string $regexCommentLine; + + private string $align; + + /** + * same spacing for all or specific for different tags. + * + * @var array|int + */ + private $spacing = 1; + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + self::ALIGN_VERTICAL]), + new CodeSample($code, ['align' => self::ALIGN_LEFT]), + new CodeSample($code, ['align' => self::ALIGN_LEFT, 'spacing' => 2]), + new CodeSample($code, ['align' => self::ALIGN_LEFT, 'spacing' => ['param' => 2]]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + */ + public function getPriority(): int + { + /* + * Should be run after all other docblock fixers. This because they + * modify other annotations to change their type and or separation + * which totally change the behaviour of this fixer. It's important that + * annotations are of the correct type, and are grouped correctly + * before running this fixer. + */ + return -42; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function configurePostNormalisation(): void + { + $tagsWithNameToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_NAME); + $tagsWithMethodSignatureToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_METHOD_SIGNATURE); + $tagsWithoutNameToAlign = array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign); + + $indentRegex = '^(?P(?:\ {2}|\t)*)\ ?'; + + $types = []; + + // e.g. @param <$var> + if ([] !== $tagsWithNameToAlign) { + $types[] = '(?P'.implode('|', $tagsWithNameToAlign).')\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?)\s*(?P(?:&|\.{3})?\$\S+)'; + } + + // e.g. @return + if ([] !== $tagsWithoutNameToAlign) { + $types[] = '(?P'.implode('|', $tagsWithoutNameToAlign).')\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?)'; + } + + // e.g. @method + if ([] !== $tagsWithMethodSignatureToAlign) { + $types[] = '(?P'.implode('|', $tagsWithMethodSignatureToAlign).')(\s+(?Pstatic))?(\s+(?P(?:'.TypeExpression::REGEX_TYPES.')?))\s+(?P.+\))'; + } + + // optional + $desc = '(?:\s+(?P\V*))'; + + $this->regex = '/'.$indentRegex.'\*\h*@(?J)(?:'.implode('|', $types).')'.$desc.'\h*\r?$/'; + $this->regexCommentLine = '/'.$indentRegex.'\*(?!\h?+@)(?:\s+(?P\V+))(?align = $this->configuration['align']; + $this->spacing = $this->configuration['spacing']; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $docBlock = new DocBlock($content); + $this->fixDocBlock($docBlock); + $newContent = $docBlock->getContent(); + if ($newContent !== $content) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $newContent]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowPositiveIntegers = static function ($value) { + $spacings = \is_array($value) ? $value : [$value]; + foreach ($spacings as $val) { + if (\is_int($val) && $val <= 0) { + throw new InvalidOptionsException('The option "spacing" is invalid. All spacings must be greater than zero.'); + } + } + + return true; + }; + + $tags = new FixerOptionBuilder( + 'tags', + 'The tags that should be aligned. Allowed values are tags with name (`\''.implode('\', \'', self::TAGS_WITH_NAME).'\'`), tags with method signature (`\''.implode('\', \'', self::TAGS_WITH_METHOD_SIGNATURE).'\'`) and any custom tag with description (e.g. `@tag `).', + ); + $tags + ->setAllowedTypes(['string[]']) + ->setDefault(self::DEFAULT_TAGS) + ; + + $align = new FixerOptionBuilder('align', 'How comments should be aligned.'); + $align + ->setAllowedTypes(['string']) + ->setAllowedValues([self::ALIGN_LEFT, self::ALIGN_VERTICAL]) + ->setDefault(self::ALIGN_VERTICAL) + ; + + $spacing = new FixerOptionBuilder( + 'spacing', + 'Spacing between tag, hint, comment, signature, etc. You can set same spacing for all tags using a positive integer or different spacings for different tags using an associative array of positive integers `[\'tagA\' => spacingForA, \'tagB\' => spacingForB]`. If you want to define default spacing to more than 1 space use `_default` key in config array, e.g.: `[\'tagA\' => spacingForA, \'tagB\' => spacingForB, \'_default\' => spacingForAllOthers]`.', + ); + $spacing->setAllowedTypes(['int', 'array']) + ->setAllowedValues([$allowPositiveIntegers]) + ->setDefault(self::DEFAULT_SPACING) + ; + + return new FixerConfigurationResolver([$tags->getOption(), $align->getOption(), $spacing->getOption()]); + } + + private function fixDocBlock(DocBlock $docBlock): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($i = 0, $l = \count($docBlock->getLines()); $i < $l; ++$i) { + $matches = $this->getMatches($docBlock->getLine($i)->getContent()); + + if (null === $matches) { + continue; + } + + $current = $i; + $items = [$matches]; + + while (true) { + if (null === $docBlock->getLine(++$i)) { + break 2; + } + + $matches = $this->getMatches($docBlock->getLine($i)->getContent(), true); + if (null === $matches) { + break; + } + + $items[] = $matches; + } + + // compute the max length of the tag, hint and variables + $hasStatic = false; + $tagMax = 0; + $hintMax = 0; + $varMax = 0; + + foreach ($items as $item) { + if (null === $item['tag']) { + continue; + } + + $hasStatic = $hasStatic || '' !== $item['static']; + $tagMax = max($tagMax, \strlen($item['tag'])); + $hintMax = max($hintMax, \strlen($item['hint'])); + $varMax = max($varMax, \strlen($item['var'])); + } + + $itemOpeningLine = null; + + $currTag = null; + $spacingForTag = $this->spacingForTag($currTag); + + // update + foreach ($items as $j => $item) { + \assert(isset($item['desc'])); + + if (null === $item['tag']) { + if ('@' === $item['desc'][0]) { + $line = $item['indent'].' * '.$item['desc']; + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + + continue; + } + + $extraIndent = 2 * $spacingForTag; + + if (\in_array($itemOpeningLine['tag'], self::TAGS_WITH_NAME, true) || \in_array($itemOpeningLine['tag'], self::TAGS_WITH_METHOD_SIGNATURE, true)) { + $extraIndent += $varMax + $spacingForTag; + } + + if ($hasStatic) { + $extraIndent += 7; // \strlen('static '); + } + + $line = $item['indent'] + .' * ' + .('' !== $itemOpeningLine['hint'] ? ' ' : '') + .$this->getIndent( + $tagMax + $hintMax + $extraIndent, + $this->getLeftAlignedDescriptionIndent($items, $j), + ) + .$item['desc']; + + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + + continue; + } + + $currTag = $item['tag']; + + $spacingForTag = $this->spacingForTag($currTag); + + $itemOpeningLine = $item; + + $line = $item['indent'] + .' * @' + .$item['tag']; + + if ($hasStatic) { + $line .= $this->getIndent( + $tagMax - \strlen($item['tag']) + $spacingForTag, + '' !== $item['static'] ? $spacingForTag : 0, + ) + .('' !== $item['static'] ? $item['static'] : $this->getIndent(6 /* \strlen('static') */, 0)); + $hintVerticalAlignIndent = $spacingForTag; + } else { + $hintVerticalAlignIndent = $tagMax - \strlen($item['tag']) + $spacingForTag; + } + + $line .= $this->getIndent( + $hintVerticalAlignIndent, + '' !== $item['hint'] ? $spacingForTag : 0, + ) + .$item['hint']; + + if ('' !== $item['var']) { + $line .= $this->getIndent((0 !== $hintMax ? $hintMax : -1) - mb_strlen($item['hint']) + $spacingForTag, $spacingForTag) + .$item['var'] + .( + '' !== $item['desc'] + ? $this->getIndent($varMax - \strlen($item['var']) + $spacingForTag, $spacingForTag).$item['desc'] + : '' + ); + } elseif ('' !== $item['desc']) { + $line .= $this->getIndent($hintMax - \strlen($item['hint']) + $spacingForTag, $spacingForTag).$item['desc']; + } + + $docBlock->getLine($current + $j)->setContent($line.$lineEnding); + } + } + } + + private function spacingForTag(?string $tag): int + { + return (\is_int($this->spacing)) + ? $this->spacing + : ($this->spacing[$tag ?? ''] ?? $this->spacing[self::DEFAULT_SPACING_KEY] ?? self::DEFAULT_SPACING); + } + + /** + * @TODO Introduce proper DTO instead of an array + * + * @return null|array{indent: null|string, tag: null|string, hint: string, var: null|string, static: string, desc?: null|string} + */ + private function getMatches(string $line, bool $matchCommentOnly = false): ?array + { + if (Preg::match($this->regex, $line, $matches)) { + if (isset($matches['tag2']) && '' !== $matches['tag2']) { + \assert(isset($matches['hint2'])); + $matches['tag'] = $matches['tag2']; + $matches['hint'] = $matches['hint2']; + $matches['var'] = ''; + } + + if (isset($matches['tag3']) && '' !== $matches['tag3']) { + \assert(isset($matches['hint3'], $matches['signature'], $matches['static'])); + $matches['tag'] = $matches['tag3']; + $matches['hint'] = $matches['hint3']; + $matches['var'] = $matches['signature']; + + // Since static can be both a return type declaration & a keyword that defines static methods + // we assume it's a type declaration when only one value is present + if ('' === $matches['hint'] && '' !== $matches['static']) { + $matches['hint'] = $matches['static']; + $matches['static'] = ''; + } + } + + if (isset($matches['hint'])) { + $matches['hint'] = trim($matches['hint']); + } + + $matches['static'] ??= ''; + + return $matches; + } + + if ($matchCommentOnly && Preg::match($this->regexCommentLine, $line, $matches)) { + $matches['tag'] = null; + $matches['var'] = ''; + $matches['hint'] = ''; + $matches['static'] = ''; + + return $matches; + } + + return null; + } + + private function getIndent(int $verticalAlignIndent, int $leftAlignIndent = 1): string + { + $indent = self::ALIGN_VERTICAL === $this->align ? $verticalAlignIndent : $leftAlignIndent; + + return str_repeat(' ', $indent); + } + + /** + * @param non-empty-list $items + */ + private function getLeftAlignedDescriptionIndent(array $items, int $index): int + { + if (self::ALIGN_LEFT !== $this->align) { + return 0; + } + + // Find last tagged line: + $item = null; + for (; $index >= 0; --$index) { + \assert(isset($items[$index])); + $item = $items[$index]; + if (null !== $item['tag']) { + break; + } + } + + // No last tag found — no indent: + if (null === $item) { + return 0; + } + + $spacingForTag = $this->spacingForTag($item['tag']); + + // Indent according to existing values: + return + $this->getSentenceIndent($item['static'], $spacingForTag) + + $this->getSentenceIndent($item['tag'], $spacingForTag) + + $this->getSentenceIndent($item['hint'], $spacingForTag) + + $this->getSentenceIndent($item['var'], $spacingForTag); + } + + /** + * Get indent for sentence. + */ + private function getSentenceIndent(?string $sentence, int $spacingForTag = 1): int + { + if (null === $sentence) { + return 0; + } + + $length = \strlen($sentence); + + return 0 === $length ? 0 : $length + $spacingForTag; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php new file mode 100644 index 0000000..991b616 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocAnnotationWithoutDotFixer extends AbstractFixer +{ + /** + * @var non-empty-list + */ + private array $tags = ['throws', 'return', 'param', 'internal', 'deprecated', 'var', 'type']; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc annotation descriptions should not be a sentence.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotations(); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + if ( + !$annotation->getTag()->valid() || !\in_array($annotation->getTag()->getName(), $this->tags, true) + ) { + continue; + } + + $lineAfterAnnotation = $doc->getLine($annotation->getEnd() + 1); + if (null !== $lineAfterAnnotation) { + $lineAfterAnnotationTrimmed = ltrim($lineAfterAnnotation->getContent()); + if ('' === $lineAfterAnnotationTrimmed || !str_starts_with($lineAfterAnnotationTrimmed, '*')) { + // malformed PHPDoc, missing asterisk ! + continue; + } + } + + $content = $annotation->getContent(); + + if ( + !Preg::match('/[.。]\h*$/u', $content) + || Preg::match('/[.。](?!\h*$)/u', $content, $matches) + ) { + continue; + } + + $endLine = $doc->getLine($annotation->getEnd()); + $endLine->setContent(Preg::replace('/(?getContent())); + + $startLine = $doc->getLine($annotation->getStart()); + $optionalTypeRegEx = $annotation->supportTypes() + ? \sprintf('(?:%s\s+(?:\$\w+\s+)?)', preg_quote(implode('|', $annotation->getTypes()), '/')) + : ''; + $content = Preg::replaceCallback( + '/^(\s*\*\s*@\w+\s+'.$optionalTypeRegEx.')(\p{Lu}?(?=\p{Ll}|\p{Zs}))(.*)$/', + static fn (array $matches): string => $matches[1].mb_strtolower($matches[2]).$matches[3], + $startLine->getContent(), + 1, + ); + $startLine->setContent($content); + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocArrayTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocArrayTypeFixer.php new file mode 100644 index 0000000..54e82ae --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocArrayTypeFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocArrayTypeFixer extends AbstractPhpdocTypesFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc `array` type must be used instead of `T[]`.', + [ + new CodeSample( + <<<'PHP' + ', $level); + }, + $type, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php new file mode 100644 index 0000000..f797279 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php @@ -0,0 +1,149 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; + +/** + * @author Ceeram + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocIndentFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Docblocks should have the same indentation as the documented subject.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + // skip if there is no next token or if next token is block end `}` + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + continue; + } + + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + + // ignore inline docblocks + if ( + $prevToken->isGivenKind(\T_OPEN_TAG) + || ($prevToken->isWhitespace(" \t") && !$tokens[$index - 2]->isGivenKind(\T_OPEN_TAG)) + || $prevToken->equalsAny([';', ',', '{', '(']) + ) { + continue; + } + + if ($tokens[$nextIndex - 1]->isWhitespace()) { + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]); + } else { + $indent = ''; + } + + $newPrevContent = $this->fixWhitespaceBeforeDocblock($prevToken->getContent(), $indent); + + $tokens[$index] = new Token([\T_DOC_COMMENT, $this->fixDocBlock($token->getContent(), $indent)]); + + if (!$prevToken->isWhitespace()) { + if ('' !== $indent) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, $indent])); + } + } elseif ('' !== $newPrevContent) { + if ($prevToken->isArray()) { + $tokens[$prevIndex] = new Token([$prevToken->getId(), $newPrevContent]); + } else { + $tokens[$prevIndex] = new Token($newPrevContent); + } + } else { + $tokens->clearAt($prevIndex); + } + } + } + + /** + * Fix indentation of Docblock. + * + * @param string $content Docblock contents + * @param string $indent Indentation to apply + * + * @return string Dockblock contents including correct indentation + */ + private function fixDocBlock(string $content, string $indent): string + { + return ltrim(Preg::replace('/^\h*\*/m', $indent.' *', $content)); + } + + /** + * @param string $content Whitespace before Docblock + * @param string $indent Indentation of the documented subject + * + * @return string Whitespace including correct indentation for Dockblock after this whitespace + */ + private function fixWhitespaceBeforeDocblock(string $content, string $indent): string + { + return rtrim($content, " \t").$indent; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php new file mode 100644 index 0000000..af43036 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocInlineTagNormalizerFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes PHPDoc inline tags.', + [ + new CodeSample( + " ['TUTORIAL']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets, + // remove spaces between '{' and '@', remove white space between end + // of text and closing bracket and between the tag and inline comment. + $content = Preg::replaceCallback( + \sprintf( + '#(?:@{+|{+\h*@)\h*(%s)\b([^}]*)(?:}+)#i', + implode('|', array_map(static fn (string $tag): string => preg_quote($tag, '/'), $this->configuration['tags'])), + ), + static function (array $matches): string { + \assert(isset($matches[1], $matches[2])); + $doc = trim($matches[2]); + + if ('' === $doc) { + return '{@'.$matches[1].'}'; + } + + return '{@'.$matches[1].' '.$doc.'}'; + }, + $token->getContent(), + ); + + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'The list of tags to normalize.')) + ->setAllowedTypes(['string[]']) + ->setDefault(['example', 'id', 'internal', 'inheritdoc', 'inheritdocs', 'link', 'source', 'toc', 'tutorial']) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php new file mode 100644 index 0000000..e90c807 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php @@ -0,0 +1,270 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case?: 'multi'|'single'|null, + * class?: 'multi'|'single'|null, + * const?: 'multi'|'single'|null, + * function?: 'multi'|'single'|null, + * method?: 'multi'|'single'|null, + * other?: 'multi'|'single'|null, + * property?: 'multi'|'single'|null, + * trait_import?: 'multi'|'single'|null, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case: 'multi'|'single'|null, + * class: 'multi'|'single'|null, + * const: 'multi'|'single'|null, + * function: 'multi'|'single'|null, + * method: 'multi'|'single'|null, + * other: 'multi'|'single'|null, + * property: 'multi'|'single'|null, + * trait_import: 'multi'|'single'|null, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gert de Pagter + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocLineSpanFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + private const PROPERTY_PART_KINDS = [ + \T_PUBLIC, + \T_PROTECTED, + \T_PRIVATE, + \T_FINAL, + \T_ABSTRACT, + \T_COMMENT, + \T_VAR, + \T_STATIC, + \T_STRING, + \T_NS_SEPARATOR, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_ARRAY_TYPEHINT, + CT::T_NULLABLE_TYPE, + CT::T_TYPE_ALTERNATION, + CT::T_TYPE_INTERSECTION, + FCT::T_ATTRIBUTE, + FCT::T_READONLY, + FCT::T_PRIVATE_SET, + FCT::T_PROTECTED_SET, + FCT::T_PUBLIC_SET, + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Changes doc blocks from single to multi line, or reversed.', + [ + new CodeSample(" 'single'], + ), + new CodeSample( + " 'multi'], + ), + new CodeSample( + <<<'PHP' + 'single'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, NoSuperfluousPhpdocTagsFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 5; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('class', 'Whether class/interface/enum/trait blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('trait_import', 'Whether trait usage blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault(null) + ->getOption(), + (new FixerOptionBuilder('const', 'Whether const blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('property', 'Whether property doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('method', 'Whether method doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('case', 'Whether enum case doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('function', 'Whether function declaration doc blocks should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault('multi') + ->getOption(), + (new FixerOptionBuilder('other', 'Whether blocks for other code lines should be single or multi line.')) + ->setAllowedValues(['single', 'multi', null]) + ->setDefault(null) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + $handled = []; + foreach ($analyzer->getClassyElements() as $index => $element) { + $type = $element['type']; + $type = 'promoted_property' === $type ? 'property' : $type; + + $docIndex = $this->getDocBlockIndex($tokens, $index); + if (null === $docIndex) { + continue; + } + + $handled[$docIndex] = true; + $this->fixDocBlock($tokens, $docIndex, $type); + } + + if ( + !isset($this->configuration['class']) + && !isset($this->configuration['function']) + && !isset($this->configuration['other']) + ) { + return; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (isset($handled[$index])) { + continue; + } + + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_FUNCTION) && !$analyzer->isLambda($index)) { + $docIndex = $this->getDocBlockIndex($tokens, $index); + + if (null === $docIndex || isset($handled[$docIndex])) { + continue; + } + + $handled[$docIndex] = true; + $this->fixDocBlock($tokens, $docIndex, 'function'); + + continue; + } + + if ($token->isGivenKind(\T_DOC_COMMENT)) { + $this->fixDocBlock($tokens, $index, 'other'); + + continue; + } + + if (!$token->isClassy()) { + continue; + } + + $docIndex = $this->getDocBlockIndex($tokens, $index); + if (null === $docIndex) { + continue; + } + + $handled[$docIndex] = true; + $this->fixDocBlock($tokens, $docIndex, 'class'); + } + } + + private function getDocBlockIndex(Tokens $tokens, int $index): ?int + { + do { + $index = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + } while ($tokens[$index]->isGivenKind(self::PROPERTY_PART_KINDS)); + + return $tokens[$index]->isGivenKind(\T_DOC_COMMENT) ? $index : null; + } + + private function fixDocBlock(Tokens $tokens, int $docIndex, string $type): void + { + if (!isset($this->configuration[$type])) { + return; + } + + $doc = new DocBlock($tokens[$docIndex]->getContent()); + + if ('multi' === $this->configuration[$type]) { + $doc->makeMultiLine(WhitespacesAnalyzer::detectIndent($tokens, $docIndex), $this->whitespacesConfig->getLineEnding()); + } elseif ('single' === $this->configuration[$type]) { + $doc->makeSingleLine(); + } + + $tokens->offsetSet($docIndex, new Token([\T_DOC_COMMENT, $doc->getContent()])); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocListTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocListTypeFixer.php new file mode 100644 index 0000000..6c8463c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocListTypeFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocListTypeFixer extends AbstractPhpdocTypesFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc `list` type must be used instead of `array` without a key.', + [ + new CodeSample( + <<<'PHP' + $x + * @param array> $y + */ + + PHP, + ), + ], + null, + 'Risky when `array` key should be present, but is missing.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer, PhpdocNoDuplicateTypesFixer, PhpdocTypesOrderFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 1; + } + + protected function normalize(string $type): string + { + return Preg::replace('/\barray(?=<(?:[^,<]|<[^>]+>)+(>|{|\())/i', 'list', $type); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php new file mode 100644 index 0000000..4af0fc5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoAccessFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@access` annotations must be removed from PHPDoc.', + [ + new CodeSample( + <<<'PHP' + configure( + ['annotations' => ['access'], + 'case_sensitive' => true, + ], + ); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php new file mode 100644 index 0000000..7f53cef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php @@ -0,0 +1,149 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; + +/** + * Case-sensitive tag replace fixer (does not process inline tags like {@inheritdoc}). + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * replacements?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * replacements: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoAliasTagFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'No alias PHPDoc tags should be used.', + [ + new CodeSample( + <<<'PHP' + ['link' => 'website']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocSingleLineVarSpacingFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function configurePostNormalisation(): void + { + \assert(isset($this->proxyFixers['general_phpdoc_tag_rename'])); + + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; + + try { + $generalPhpdocTagRenameFixer->configure([ + 'fix_annotation' => true, + 'fix_inline' => false, + 'replacements' => $this->configuration['replacements'], + 'case_sensitive' => true, + ]); + } catch (InvalidConfigurationException $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), + $exception, + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.')) + ->setAllowedTypes(['array']) + ->setDefault( + Future::getV4OrV3(['const' => 'var'], []) + + [ + 'property-read' => 'property', + 'property-write' => 'property', + 'type' => 'var', + 'link' => 'see', + ], + ) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [new GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoDuplicateTypesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoDuplicateTypesFixer.php new file mode 100644 index 0000000..83fd6eb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoDuplicateTypesFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoDuplicateTypesFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes duplicate PHPDoc types.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + // fix main types + if (null !== $annotation->getTypeExpression()) { + $annotation->setTypes( + $annotation->getTypeExpression() + ->removeDuplicateTypes() + ->getTypes(), + ); + } + + // fix @method parameters types + $line = $doc->getLine($annotation->getStart()); + $line->setContent(Preg::replaceCallback('/\*\h*@method\h+'.TypeExpression::REGEX_TYPES.'\h+\K(?&callable)/', static function (array $matches): string { + \assert(isset($matches[0])); + + $typeExpression = new TypeExpression($matches[0], null, []); + + return implode('|', $typeExpression->removeDuplicateTypes()->getTypes()); + }, $line->getContent())); + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php new file mode 100644 index 0000000..640b24d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoEmptyReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@return void` and `@return null` annotations must be removed from PHPDoc.', + [ + new CodeSample( + <<<'PHP' + $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType('return'); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + $this->fixAnnotation($annotation); + } + + $newContent = $doc->getContent(); + + if ($newContent === $token->getContent()) { + continue; + } + + if ('' === $newContent) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + continue; + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * Remove `return void` or `return null` annotations. + */ + private function fixAnnotation(Annotation $annotation): void + { + $types = $annotation->getNormalizedTypes(); + + if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) { + $annotation->remove(); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php new file mode 100644 index 0000000..eb69e1e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoPackageFixer extends AbstractProxyFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@package` and `@subpackage` annotations must be removed from PHPDoc.', + [ + new CodeSample( + <<<'PHP' + configure([ + 'annotations' => ['package', 'subpackage'], + 'case_sensitive' => true, + ]); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php new file mode 100644 index 0000000..9d7cd5f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php @@ -0,0 +1,153 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Remove inheritdoc tags from classy that does not inherit. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocNoUselessInheritdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Classy that does not inherit must not have `@inheritdoc` tags.', + [ + new CodeSample("isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + // min. offset 4 as minimal candidate is @: isGivenKind([\T_CLASS, \T_INTERFACE])) { + $index = $this->fixClassy($tokens, $index); + } + } + } + + private function fixClassy(Tokens $tokens, int $index): int + { + // figure out where the classy starts + $classOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); + + // figure out where the classy ends + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $classOpenIndex); + + // is classy extending or implementing some interface + $extendingOrImplementing = $this->isExtendingOrImplementing($tokens, $index, $classOpenIndex); + + if (!$extendingOrImplementing) { + // PHPDoc of classy should not have inherit tag even when using traits as Traits cannot provide this information + $this->fixClassyOutside($tokens, $index); + } + + // figure out if the classy uses a trait + if (!$extendingOrImplementing && $this->isUsingTrait($tokens, $index, $classOpenIndex, $classEndIndex)) { + $extendingOrImplementing = true; + } + + $this->fixClassyInside($tokens, $classOpenIndex, $classEndIndex, !$extendingOrImplementing); + + return $classEndIndex; + } + + private function fixClassyInside(Tokens $tokens, int $classOpenIndex, int $classEndIndex, bool $fixThisLevel): void + { + for ($i = $classOpenIndex; $i < $classEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind(\T_CLASS)) { + $i = $this->fixClassy($tokens, $i); + } elseif ($fixThisLevel && $tokens[$i]->isGivenKind(\T_DOC_COMMENT)) { + $this->fixToken($tokens, $i); + } + } + } + + private function fixClassyOutside(Tokens $tokens, int $classIndex): void + { + $previousIndex = $tokens->getPrevNonWhitespace($classIndex); + if ($tokens[$previousIndex]->isGivenKind(\T_DOC_COMMENT)) { + $this->fixToken($tokens, $previousIndex); + } + } + + private function fixToken(Tokens $tokens, int $tokenIndex): void + { + $count = 0; + $content = Preg::replaceCallback( + '#(\h*(?:@{*|{*\h*@)\h*inheritdoc\h*)([^}]*)((?:}*)\h*)#i', + static fn (array $matches): string => ' '.$matches[2], + $tokens[$tokenIndex]->getContent(), + -1, + $count, + ); + + if ($count > 0) { + $tokens[$tokenIndex] = new Token([\T_DOC_COMMENT, $content]); + } + } + + private function isExtendingOrImplementing(Tokens $tokens, int $classIndex, int $classOpenIndex): bool + { + for ($index = $classIndex; $index < $classOpenIndex; ++$index) { + if ($tokens[$index]->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { + return true; + } + } + + return false; + } + + private function isUsingTrait(Tokens $tokens, int $classIndex, int $classOpenIndex, int $classCloseIndex): bool + { + if ($tokens[$classIndex]->isGivenKind(\T_INTERFACE)) { + // cannot use Trait inside an interface + return false; + } + + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + + return null !== $useIndex && $useIndex < $classCloseIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php new file mode 100644 index 0000000..51a86f9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php @@ -0,0 +1,231 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * annotations?: list<'author'|'covers'|'coversNothing'|'dataProvider'|'depends'|'group'|'internal'|'method'|'mixin'|'property'|'property-read'|'property-write'|'requires'|'throws'|'uses'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * annotations: array{'author'?: 'author', 'covers'?: 'covers', 'coversNothing'?: 'coversnothing', 'dataProvider'?: 'dataprovider', 'depends'?: 'depends', 'group'?: 'group', 'internal'?: 'internal', 'method'?: 'method', 'mixin'?: 'mixin', 'property'?: 'property', 'property-read'?: 'property-read', 'property-write'?: 'property-write', 'requires'?: 'requires', 'throws'?: 'throws', 'uses'?: 'uses'}, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocOrderByValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Order PHPDoc tags by value.', + [ + new CodeSample( + <<<'PHP' + [ + 'author', + ], + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpUnitFqcnAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ([] === $this->configuration['annotations']) { + return; + } + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + foreach ($this->configuration['annotations'] as $type => $typeLowerCase) { + $findPattern = \sprintf( + '/@%s\s.+@%s\s/s', + $type, + $type, + ); + + if ( + !$tokens[$index]->isGivenKind(\T_DOC_COMMENT) + || !Preg::match($findPattern, $tokens[$index]->getContent()) + ) { + continue; + } + + $docBlock = new DocBlock($tokens[$index]->getContent()); + + $annotations = $docBlock->getAnnotationsOfType($type); + $annotationMap = []; + + if (\in_array($type, ['property', 'property-read', 'property-write'], true)) { + $replacePattern = \sprintf( + '/(?s)\*\s*@%s\s+(?P.+\s+)?\$(?P\S+).*/', + $type, + ); + + $replacement = '\2'; + } elseif ('method' === $type) { + $replacePattern = '/(?s)\*\s*@method\s+(?P.+\s+)?(?P.+)\(.*/'; + $replacement = '\2'; + } else { + $replacePattern = \sprintf( + '/\*\s*@%s\s+(?P.+)/', + $typeLowerCase, + ); + + $replacement = '\1'; + } + + foreach ($annotations as $annotation) { + $rawContent = $annotation->getContent(); + + $comparableContent = Preg::replace( + $replacePattern, + $replacement, + strtolower(trim($rawContent)), + ); + + $annotationMap[$comparableContent] = $rawContent; + } + + $orderedAnnotationMap = $annotationMap; + + ksort($orderedAnnotationMap, \SORT_STRING); + + if ($orderedAnnotationMap === $annotationMap) { + continue; + } + + $lines = $docBlock->getLines(); + + foreach (array_reverse($annotations) as $annotation) { + array_splice( + $lines, + $annotation->getStart(), + $annotation->getEnd() - $annotation->getStart() + 1, + array_pop($orderedAnnotationMap), + ); + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, implode('', $lines)]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowedValues = [ + 'author', + 'covers', + 'coversNothing', + 'dataProvider', + 'depends', + 'group', + 'internal', + 'method', + 'mixin', + 'property', + 'property-read', + 'property-write', + 'requires', + 'throws', + 'uses', + ]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('annotations', 'List of annotations to order, e.g. `["covers"]`.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([ + new AllowedValueSubset($allowedValues), + ]) + ->setNormalizer(static function (Options $options, array $value): array { + $normalized = []; + + foreach ($value as $annotation) { + // since we will be using "strtolower" on the input annotations when building the sorting + // map we must match the type in lower case as well + $normalized[$annotation] = strtolower($annotation); + } + + return $normalized; + }) + ->setDefault([ + 'covers', + ]) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php new file mode 100644 index 0000000..46a29f5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php @@ -0,0 +1,247 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * order?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * order: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** @var list */ + private array $configurationOrder; + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + ['param', 'return', 'throws']]), + new CodeSample($code, ['order' => ['param', 'throws', 'return']]), + new CodeSample($code, ['order' => ['param', 'custom', 'throws', 'return']]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -2; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('order', 'Sequence in which annotations in PHPDoc should be ordered.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([static function (array $order): bool { + if (\count($order) < 2) { + throw new InvalidOptionsException('The option "order" value is invalid. Minimum two tags are required.'); + } + + $unique = array_unique($order); + if (\count($order) !== \count($unique)) { + $duplicates = array_keys(array_filter(array_count_values($order), static fn (int $count): bool => $count > 1)); + + throw new InvalidOptionsException(\sprintf( + 'The option "order" value is invalid. Tag%s %s %s duplicated.', + \count($duplicates) > 1 ? 's' : '', + Utils::naturalLanguageJoin($duplicates), // @phpstan-ignore-line argument.type + \count($duplicates) > 1 ? 'are' : 'is', + )); + } + + return true; + }]) + ->setDefault(Future::getV4OrV3(['param', 'return', 'throws'], ['param', 'throws', 'return'])) + ->getOption(), + ]); + } + + protected function configurePostNormalisation(): void + { + $this->configurationOrder = []; + foreach ($this->configuration['order'] as $type) { + $this->configurationOrder[] = $type; + if (!\in_array('phpstan-'.$type, $this->configuration['order'], true)) { + $this->configurationOrder[] = 'phpstan-'.$type; + } + if (!\in_array('psalm-'.$type, $this->configuration['order'], true)) { + $this->configurationOrder[] = 'psalm-'.$type; + } + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + // assuming annotations are already grouped by tags + $content = $token->getContent(); + + // sort annotations + $successors = $this->configurationOrder; + while (\count($successors) >= 3) { + $predecessor = array_shift($successors); + $content = $this->moveAnnotationsBefore($predecessor, $successors, $content); + } + + // we're parsing the content last time to make sure the internal + // state of the docblock is correct after the modifications + $predecessors = $this->configurationOrder; + $last = array_pop($predecessors); + $content = $this->moveAnnotationsAfter($last, $predecessors, $content); + + // persist the content at the end + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + + /** + * Move all given annotations in before given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param list $before Tags of annotations that should moved annotations be placed before + */ + private function moveAnnotationsBefore(string $move, array $before, string $content): string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + + $others = $doc->getAnnotationsOfType($before); + + if (0 === \count($others)) { + return $content; + } + + // get the index of the final line of the final toBoMoved annotation + $end = end($toBeMoved)->getEnd(); + + $line = $doc->getLine($end); + + // move stuff about if required + foreach ($others as $other) { + if ($other->getStart() < $end) { + // we're doing this to maintain the original line indices + $line->setContent($line->getContent().$other->getContent()); + $other->remove(); + } + } + + return $doc->getContent(); + } + + /** + * Move all given annotations after given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param list $after Tags of annotations that should moved annotations be placed after + */ + private function moveAnnotationsAfter(string $move, array $after, string $content): string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + + $others = $doc->getAnnotationsOfType($after); + + // nothing to do if there are no other annotations + if (0 === \count($others)) { + return $content; + } + + // get the index of the first line of the first toBeMoved annotation + $start = $toBeMoved[0]->getStart(); + $line = $doc->getLine($start); + + // move stuff about if required + foreach (array_reverse($others) as $other) { + if ($other->getEnd() > $start) { + // we're doing this to maintain the original line indices + $line->setContent($other->getContent().$line->getContent()); + $other->remove(); + } + } + + return $doc->getContent(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php new file mode 100644 index 0000000..5e5adb8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php @@ -0,0 +1,273 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jonathan Gruber + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocParamOrderFixer extends AbstractFixer +{ + private const PARAM_TAG = 'param'; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Orders all `@param` annotations in DocBlocks according to method signature.', + [ + new CodeSample( + <<<'PHP' + $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + // Check for function / closure token + $nextFunctionToken = $tokens->getNextTokenOfKind($index, [[\T_FUNCTION], [\T_FN]]); + if (null === $nextFunctionToken) { + return; + } + + // Find start index of param block (opening parenthesis) + $paramBlockStart = $tokens->getNextTokenOfKind($index, ['(']); + if (null === $paramBlockStart) { + return; + } + + $doc = new DocBlock($token->getContent()); + $paramAnnotations = $doc->getAnnotationsOfType(self::PARAM_TAG); + + if ([] === $paramAnnotations) { + continue; + } + + $paramNames = $this->getFunctionParamNames($tokens, $paramBlockStart); + $doc = $this->rewriteDocBlock($doc, $paramNames, $paramAnnotations); + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * @return list + */ + private function getFunctionParamNames(Tokens $tokens, int $paramBlockStart): array + { + $paramBlockEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $paramBlockStart); + + $paramNames = []; + for ( + $i = $tokens->getNextTokenOfKind($paramBlockStart, [[\T_VARIABLE]]); + null !== $i && $i < $paramBlockEnd; + $i = $tokens->getNextTokenOfKind($i, [[\T_VARIABLE]]) + ) { + $paramNames[] = $tokens[$i]; + } + + return $paramNames; + } + + /** + * Overwrite the param annotations in order. + * + * @param list $paramNames + * @param non-empty-list $paramAnnotations + */ + private function rewriteDocBlock(DocBlock $doc, array $paramNames, array $paramAnnotations): DocBlock + { + $orderedAnnotations = $this->sortParamAnnotations($paramNames, $paramAnnotations); + $otherAnnotations = $this->getOtherAnnotationsBetweenParams($doc, $paramAnnotations); + + // Append annotations found between param ones + if ([] !== $otherAnnotations) { + array_push($orderedAnnotations, ...$otherAnnotations); + } + + // Overwrite all annotations between first and last @param tag in order + $paramsStart = reset($paramAnnotations)->getStart(); + $paramsEnd = end($paramAnnotations)->getEnd(); + + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + + $annotation->remove(); + $doc + ->getLine($annotation->getStart()) + ->setContent(current($orderedAnnotations)) + ; + + next($orderedAnnotations); + } + + return $doc; + } + + /** + * Sort the param annotations according to the function parameters. + * + * @param list $funcParamNames + * @param non-empty-list $paramAnnotations + * + * @return non-empty-list + */ + private function sortParamAnnotations(array $funcParamNames, array $paramAnnotations): array + { + $validParams = []; + foreach ($funcParamNames as $paramName) { + foreach ($this->findParamAnnotationByIdentifier($paramAnnotations, $paramName->getContent()) as $index => $annotation) { + // Found an exactly matching @param annotation + $validParams[$index] = $annotation->getContent(); + } + } + + // Detect superfluous annotations + $invalidParams = array_values( + array_diff_key($paramAnnotations, $validParams), + ); + + // Append invalid parameters to the (ordered) valid ones + $orderedParams = array_values($validParams); + foreach ($invalidParams as $params) { + $orderedParams[] = $params->getContent(); + } + \assert(\count($orderedParams) > 0); + + return $orderedParams; + } + + /** + * Fetch all annotations except the param ones. + * + * @param list $paramAnnotations + * + * @return list + */ + private function getOtherAnnotationsBetweenParams(DocBlock $doc, array $paramAnnotations): array + { + if (0 === \count($paramAnnotations)) { + return []; + } + + $paramsStart = reset($paramAnnotations)->getStart(); + $paramsEnd = end($paramAnnotations)->getEnd(); + + $otherAnnotations = []; + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + + if (self::PARAM_TAG !== $annotation->getTag()->getName()) { + $otherAnnotations[] = $annotation->getContent(); + } + } + + return $otherAnnotations; + } + + /** + * Return the indices of the lines of a specific parameter annotation. + * + * @param list $paramAnnotations + * + * @return array Mapping of found indices and corresponding Annotations + */ + private function findParamAnnotationByIdentifier(array $paramAnnotations, string $identifier): array + { + $blockLevel = 0; + $blockMatch = false; + $blockIndices = []; + + $paramRegex = '/\*\h*@param\h*(?:|'.TypeExpression::REGEX_TYPES.'\h*)&?(?=\$\b)'.preg_quote($identifier).'\b/'; + + foreach ($paramAnnotations as $i => $param) { + $blockStart = Preg::match('/\s*{\s*/', $param->getContent()); + $blockEndMatches = Preg::matchAll('/}[\*\s\n]*/', $param->getContent()); + + if (0 === $blockLevel && Preg::match($paramRegex, $param->getContent())) { + if ($blockStart) { + $blockMatch = true; // Start of a nested block + } else { + return [$i => $param]; // Top level match + } + } + + if ($blockStart) { + ++$blockLevel; + } + + if (0 !== $blockEndMatches) { + $blockLevel -= $blockEndMatches; + } + + if ($blockMatch) { + $blockIndices[$i] = $param; + if (0 === $blockLevel) { + return $blockIndices; + } + } + } + + return []; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php new file mode 100644 index 0000000..98eaf8f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php @@ -0,0 +1,238 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * replacements?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * replacements: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocReturnSelfReferenceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var non-empty-list + */ + private const TO_TYPES = [ + '$this', + 'static', + 'self', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The type of `@return` annotations of methods returning a reference to itself must the configured one.', + [ + new CodeSample( + <<<'PHP' + ['this' => 'self']], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return \count($tokens) > 10 && $tokens->isAllTokenKindsFound([\T_DOC_COMMENT, \T_FUNCTION]) && $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 10; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { + if ('method' === $element['type']) { + $this->fixMethod($tokens, $index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $default = [ + 'this' => '$this', + '@this' => '$this', + '$self' => 'self', + '@self' => 'self', + '$static' => 'static', + '@static' => 'static', + ]; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('replacements', 'Mapping between replaced return types with new ones.')) + ->setAllowedTypes(['array']) + ->setNormalizer(static function (Options $options, array $value) use ($default): array { + $normalizedValue = []; + + foreach ($value as $from => $to) { + if (\is_string($from)) { + $from = strtolower($from); + } + + if (!isset($default[$from])) { + throw new InvalidOptionsException(\sprintf( + 'Unknown key "%s", expected any of %s.', + \gettype($from).'#'.$from, + Utils::naturalLanguageJoin(array_keys($default)), + )); + } + + if (!\in_array($to, self::TO_TYPES, true)) { + throw new InvalidOptionsException(\sprintf( + 'Unknown value "%s", expected any of %s.', + \is_object($to) ? \get_class($to) : \gettype($to).(\is_resource($to) ? '' : '#'.$to), + Utils::naturalLanguageJoin(self::TO_TYPES), + )); + } + + $normalizedValue[$from] = $to; + } + + return $normalizedValue; + }) + ->setDefault($default) + ->getOption(), + ]); + } + + private function fixMethod(Tokens $tokens, int $index): void + { + // find PHPDoc of method (if any) + while (true) { + $tokenIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$tokenIndex]->isGivenKind([\T_STATIC, \T_FINAL, \T_ABSTRACT, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC])) { + break; + } + + $index = $tokenIndex; + } + + $docIndex = $tokens->getPrevNonWhitespace($index); + if (!$tokens[$docIndex]->isGivenKind(\T_DOC_COMMENT)) { + return; + } + + // find @return + $docBlock = new DocBlock($tokens[$docIndex]->getContent()); + $returnsBlock = $docBlock->getAnnotationsOfType('return'); + + if (0 === \count($returnsBlock)) { + return; // no return annotation found + } + + $returnsBlock = $returnsBlock[0]; + $types = $returnsBlock->getTypes(); + + if (0 === \count($types)) { + return; // no return type(s) found + } + + $newTypes = []; + + foreach ($types as $type) { + $newTypes[] = $this->configuration['replacements'][strtolower($type)] ?? $type; + } + + if ($types === $newTypes) { + return; + } + + $returnsBlock->setTypes($newTypes); + $tokens[$docIndex] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php new file mode 100644 index 0000000..5b84caf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php @@ -0,0 +1,152 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * types?: list<'boolean'|'callback'|'double'|'integer'|'never-return'|'never-returns'|'no-return'|'real'|'str'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * types: list<'boolean'|'callback'|'double'|'integer'|'never-return'|'never-returns'|'no-return'|'real'|'str'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocScalarFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * The types to fix. + */ + private const TYPES_MAP = [ + 'boolean' => 'bool', + 'callback' => 'callable', + 'double' => 'float', + 'integer' => 'int', + 'never-return' => 'never', + 'never-returns' => 'never', + 'no-return' => 'never', + 'real' => 'float', + 'str' => 'string', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Scalar types should always be written in the same form. `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`.', + [ + new CodeSample( + <<<'PHP' + ['boolean']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocTypesFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run after + * the phpdoc_types_fixer because it can convert types to things that + * we can fix. + */ + return 15; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $defaultTypes = ['boolean', 'callback', 'double', 'integer', 'real', 'str']; + $allowedTypes = array_keys(self::TYPES_MAP); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('types', 'A list of types to fix.')) + ->setAllowedValues([new AllowedValueSubset($allowedTypes)]) + ->setDefault(Future::getV4OrV3($allowedTypes, $defaultTypes)) + ->getOption(), + ]); + } + + protected function normalize(string $type): string + { + $suffix = ''; + while (str_ends_with($type, '[]')) { + $type = substr($type, 0, -2); + $suffix .= '[]'; + } + + if (\in_array($type, $this->configuration['types'], true)) { + $type = self::TYPES_MAP[$type]; + } + + return $type.$suffix; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php new file mode 100644 index 0000000..db7de52 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php @@ -0,0 +1,336 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * groups?: list>, + * skip_unlisted_annotations?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * groups: list>, + * skip_unlisted_annotations: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + * + * @var non-empty-list> + */ + public const OPTION_GROUPS_DEFAULT = [ + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ['deprecated', 'link', 'see', 'since'], + ]; + + /** + * @var list> + */ + private array $groups; + + public function getDefinition(): FixerDefinitionInterface + { + $code = <<<'EOF' + [ + ['deprecated', 'link', 'see', 'since'], + ['author', 'copyright', 'license'], + ['category', 'package', 'subpackage'], + ['property', 'property-read', 'property-write'], + ['param', 'return'], + ]]), + new CodeSample($code, ['groups' => [ + ['author', 'throws', 'custom'], + ['return', 'param'], + ]]), + new CodeSample( + <<<'EOF' + [['ORM\*'], ['Assert\*']]], + ), + new CodeSample($code, ['skip_unlisted_annotations' => true]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpUnitAttributesFixer, PhpUnitInternalClassFixer, PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocOrderFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return -3; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function configurePostNormalisation(): void + { + $this->groups = $this->configuration['groups']; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $this->fixDescription($doc); + $this->fixAnnotations($doc); + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $allowTagToBelongToOnlyOneGroup = static function (array $groups): bool { + $tags = []; + foreach ($groups as $groupIndex => $group) { + foreach ($group as $member) { + if (isset($tags[$member])) { + if ($groupIndex === $tags[$member]) { + throw new InvalidOptionsException( + 'The option "groups" value is invalid. ' + .'The "'.$member.'" tag is specified more than once.', + ); + } + + throw new InvalidOptionsException( + 'The option "groups" value is invalid. ' + .'The "'.$member.'" tag belongs to more than one group.', + ); + } + $tags[$member] = $groupIndex; + } + } + + return true; + }; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('groups', 'Sets of annotation types to be grouped together. Use `*` to match any tag character.')) + ->setAllowedTypes(['string[][]']) + ->setDefault(self::OPTION_GROUPS_DEFAULT) + ->setAllowedValues([$allowTagToBelongToOnlyOneGroup]) + ->getOption(), + (new FixerOptionBuilder('skip_unlisted_annotations', 'Whether to skip annotations that are not listed in any group.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + ]); + } + + /** + * Make sure the description is separated from the annotations. + */ + private function fixDescription(DocBlock $doc): void + { + foreach ($doc->getLines() as $index => $line) { + if ($line->containsATag()) { + break; + } + + if ($line->containsUsefulContent()) { + $next = $doc->getLine($index + 1); + + if (null !== $next && $next->containsATag()) { + $line->addBlank(); + + break; + } + } + } + } + + /** + * Make sure the annotations are correctly separated. + */ + private function fixAnnotations(DocBlock $doc): void + { + foreach ($doc->getAnnotations() as $index => $annotation) { + $next = $doc->getAnnotation($index + 1); + + if (null === $next) { + break; + } + + $shouldBeTogether = $this->shouldBeTogether($annotation, $next, $this->groups); + + if (true === $shouldBeTogether) { + $this->ensureAreTogether($doc, $annotation, $next); + } elseif (false === $shouldBeTogether || false === $this->configuration['skip_unlisted_annotations']) { + $this->ensureAreSeparate($doc, $annotation, $next); + } + } + } + + /** + * Force the given annotations to immediately follow each other. + */ + private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second): void + { + $pos = $first->getEnd(); + $final = $second->getStart(); + + for (++$pos; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + + /** + * Force the given annotations to have one empty line between each other. + */ + private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second): void + { + $pos = $first->getEnd(); + $final = $second->getStart() - 1; + + // check if we need to add a line, or need to remove one or more lines + if ($pos === $final) { + $doc->getLine($pos)->addBlank(); + + return; + } + + for (++$pos; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + + /** + * @param list> $groups + */ + private function shouldBeTogether(Annotation $first, Annotation $second, array $groups): ?bool + { + $firstName = $this->tagName($first); + $secondName = $this->tagName($second); + + // A tag could not be read. + if (null === $firstName || null === $secondName) { + return null; + } + + if ($firstName === $secondName) { + return true; + } + + foreach ($groups as $group) { + $firstTagIsInGroup = $this->isInGroup($firstName, $group); + $secondTagIsInGroup = $this->isInGroup($secondName, $group); + + if ($firstTagIsInGroup) { + return $secondTagIsInGroup; + } + + if ($secondTagIsInGroup) { + return false; + } + } + + return null; + } + + private function tagName(Annotation $annotation): ?string + { + Preg::match('/@([a-zA-Z0-9_\\\-]+(?=\s|$|\())/', $annotation->getContent(), $matches); + + return $matches[1] ?? null; + } + + /** + * @param list $group + */ + private function isInGroup(string $tag, array $group): bool + { + foreach ($group as $tagInGroup) { + $tagInGroup = str_replace('*', '\*', $tagInGroup); + $tagInGroup = preg_quote($tagInGroup, '/'); + $tagInGroup = str_replace('\\\\\*', '.*?', $tagInGroup); + + if (Preg::match("/^{$tagInGroup}$/", $tag)) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php new file mode 100644 index 0000000..0dc2f97 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for part of rule defined in PSR5 ¶7.22. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single line `@var` PHPDoc should have proper spacing.', + [new CodeSample("isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isComment()) { + continue; + } + + $content = $token->getContent(); + $fixedContent = $this->fixTokenContent($content); + + if ($content !== $fixedContent) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $fixedContent]); + } + } + } + + private function fixTokenContent(string $content): string + { + return Preg::replaceCallback( + '#^/\*\*\h*@var\h+(\S+)\h*(\$\S+)?\h*([^\n]*)\*/$#', + static function (array $matches) { + $content = '/** @var'; + + for ($i = 1, $m = \count($matches); $i < $m; ++$i) { + \assert(isset($matches[$i])); + if ('' !== $matches[$i]) { + $content .= ' '.$matches[$i]; + } + } + + return rtrim($content).' */'; + }, + $content, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php new file mode 100644 index 0000000..e83b782 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php @@ -0,0 +1,107 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\ShortDescription; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc summary should end in either a full stop, exclamation mark, or question mark.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $end = (new ShortDescription($doc))->getEnd(); + + if (null !== $end) { + $line = $doc->getLine($end); + $content = rtrim($line->getContent()); + + if ( + // final line of Description is NOT properly formatted + !$this->isCorrectlyFormatted($content) + // and first line of Description, if different than final line, does NOT indicate a list + && (1 === $end || ($doc->isMultiLine() && ':' !== substr(rtrim($doc->getLine(1)->getContent()), -1))) + ) { + $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding()); + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + } + } + + /** + * Is the last line of the short description correctly formatted? + */ + private function isCorrectlyFormatted(string $content): bool + { + if (str_contains(strtolower($content), strtolower('{@inheritdoc}'))) { + return true; + } + + return $content !== rtrim($content, '.:。!?¡¿!?'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php new file mode 100644 index 0000000..ad8a184 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTagCasingFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fixes casing of PHPDoc tags.', + [ + new CodeSample(" ['foo'], + ]), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function configurePostNormalisation(): void + { + $replacements = []; + foreach ($this->configuration['tags'] as $tag) { + $replacements[$tag] = $tag; + } + + \assert(isset($this->proxyFixers['general_phpdoc_tag_rename'])); + + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; + + try { + $generalPhpdocTagRenameFixer->configure([ + 'case_sensitive' => false, + 'fix_annotation' => true, + 'fix_inline' => true, + 'replacements' => $replacements, + ]); + } catch (InvalidConfigurationException $exception) { + throw new InvalidFixerConfigurationException( + $this->getName(), + Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), + $exception, + ); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'List of tags to fix with their expected casing.')) + ->setAllowedTypes(['string[]']) + ->setDefault(['inheritDoc']) + ->getOption(), + ]); + } + + protected function createProxyFixers(): array + { + return [new GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagNoNamedArgumentsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagNoNamedArgumentsFixer.php new file mode 100644 index 0000000..4931037 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagNoNamedArgumentsFixer.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DocBlockAnnotationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * description?: string, + * fix_attribute?: bool, + * fix_internal?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * description: string, + * fix_attribute: bool, + * fix_internal: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTagNoNamedArgumentsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + use DocBlockAnnotationTrait; + + public function getDefinition(): FixerDefinitionInterface + { + $code + = <<<'PHP' + 'Parameter names are not covered by the backward compatibility promise.']), + ], + ); + } + + public function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('description', 'Description of the tag.')) + ->setAllowedTypes(['string']) + ->setDefault('') + ->getOption(), + (new FixerOptionBuilder('fix_attribute', 'Whether to fix attribute classes.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('fix_internal', 'Whether to fix internal elements (marked with `@internal`).')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isClassy()) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + \assert(\is_int($prevIndex)); + + if ($tokens[$prevIndex]->isGivenKind(\T_NEW)) { + continue; + } + + if (!$this->configuration['fix_attribute'] && self::isAttributeClass($tokens, $prevIndex)) { + continue; + } + + $this->ensureIsDocBlockWithAnnotation( + $tokens, + $index, + 'no-named-arguments', + $this->configuration['fix_internal'] ? ['no-named-arguments'] : ['internal', 'no-named-arguments'], + [], + ); + + $docBlockIndex = $tokens->getPrevTokenOfKind($index + 2, [[\T_DOC_COMMENT]]); + \assert(\is_int($docBlockIndex)); + + $content = $tokens[$docBlockIndex]->getContent(); + + $newContent = Preg::replace('/@no-named-arguments.*\R/', rtrim('@no-named-arguments '.$this->configuration['description']).$this->whitespacesConfig->getLineEnding(), $content); + + if ($newContent !== $content) { + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $newContent]); + } + } + } + + private static function isAttributeClass(Tokens $tokens, int $index): bool + { + while ($tokens[$index]->isGivenKind([\T_FINAL, FCT::T_READONLY])) { + $index = $tokens->getPrevMeaningfulToken($index); + \assert(\is_int($index)); + } + + if (!$tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + return false; + } + + $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); + + foreach (AttributeAnalyzer::collect($tokens, $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index)) as $attributeAnalysis) { + foreach ($attributeAnalysis->getAttributes() as $attribute) { + $attributeName = strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)); + if ('attribute' === $attributeName) { + return true; + } + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php new file mode 100644 index 0000000..85cff39 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * tags?: array, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * tags: array, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTagTypeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const TAG_REGEX = '/^(?: + (? + (?:@(?.+?)(?:\s.+)?) + ) + | + {(? + (?:@(?.+?)(?:\s.+)?) + )} + )$/x'; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Forces PHPDoc tags to be either regular annotations or inline.', + [ + new CodeSample( + " ['inheritdoc' => 'inline']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + + $regularExpression = \sprintf( + '/({?@(?:%s).*?(?:(?=\s\*\/)|(?=\n)}?))/i', + implode('|', array_map( + static fn (string $tag): string => preg_quote($tag, '/'), + array_keys($this->configuration['tags']), + )), + ); + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $parts = Preg::split( + $regularExpression, + $token->getContent(), + -1, + \PREG_SPLIT_DELIM_CAPTURE, + ); + + for ($i = 1, $max = \count($parts) - 1; $i < $max; $i += 2) { + \assert(isset($parts[$i])); + if (!Preg::match(self::TAG_REGEX, $parts[$i], $matches)) { + continue; + } + + if ('' !== $matches['tag']) { + $tag = $matches['tag']; + $tagName = $matches['tag_name']; + } else { + $tag = $matches['inlined_tag']; + $tagName = $matches['inlined_tag_name']; + } + + $tagName = strtolower($tagName); + if (!isset($this->configuration['tags'][$tagName])) { + continue; + } + + if ('inline' === $this->configuration['tags'][$tagName]) { + $parts[$i] = '{'.$tag.'}'; + + continue; + } + + if (!$this->tagIsSurroundedByText($parts, $i)) { + $parts[$i] = $tag; + } + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, implode('', $parts)]); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tags', 'The list of tags to fix.')) + ->setAllowedTypes(["array"]) + ->setAllowedValues([static function (array $value): bool { + foreach ($value as $type) { + if (!\in_array($type, ['annotation', 'inline'], true)) { + throw new InvalidOptionsException("Unknown tag type \"{$type}\"."); + } + } + + return true; + }]) + ->setDefault([ + 'api' => 'annotation', + 'author' => 'annotation', + 'copyright' => 'annotation', + 'deprecated' => 'annotation', + 'example' => 'annotation', + 'global' => 'annotation', + 'inheritDoc' => 'annotation', + 'internal' => 'annotation', + 'license' => 'annotation', + 'method' => 'annotation', + 'package' => 'annotation', + 'param' => 'annotation', + 'property' => 'annotation', + 'return' => 'annotation', + 'see' => 'annotation', + 'since' => 'annotation', + 'throws' => 'annotation', + 'todo' => 'annotation', + 'uses' => 'annotation', + 'var' => 'annotation', + 'version' => 'annotation', + ]) + ->setNormalizer(static function (Options $options, array $value): array { + $normalized = []; + + foreach ($value as $tag => $type) { + $normalized[strtolower($tag)] = $type; + } + + return $normalized; + }) + ->getOption(), + ]); + } + + /** + * @param array $parts + */ + private function tagIsSurroundedByText(array $parts, int $index): bool + { + \assert(isset($parts[$index - 1], $parts[$index + 1])); + + return + Preg::match('/(^|\R)\h*[^@\s]\N*/', $this->cleanComment($parts[$index - 1])) + || Preg::match('/^.*?\R\s*[^@\s]/', $this->cleanComment($parts[$index + 1])); + } + + private function cleanComment(string $comment): string + { + $comment = Preg::replace('/^\/\*\*|\*\/$/', '', $comment); + + return Preg::replace('/(\R)(\h*\*)?\h*/', '$1', $comment); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php new file mode 100644 index 0000000..284631b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php @@ -0,0 +1,194 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * allow_before_return_statement?: bool, + * ignored_tags?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * allow_before_return_statement: bool, + * ignored_tags: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Ceeram + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocToCommentFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var list + */ + private array $ignoredTags = []; + private bool $allowBeforeReturnStatement = false; + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentSpacingFixer, SingleLineCommentStyleFixer. + * Must run after CommentToPhpdocFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers so that these fixers + * don't touch doc comments which are meant to be converted to regular + * comments. + */ + return 25; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Docblocks should only be used on structural elements.', + [ + new CodeSample( + <<<'PHP' + $sqlite) { + $sqlite->open($path); + } + + PHP, + ), + new CodeSample( + <<<'PHP' + $sqlite) { + $sqlite->open($path); + } + + /** @todo This should be a PHPDoc as the tag is on "ignored_tags" list */ + foreach($connections as $key => $sqlite) { + $sqlite->open($path); + } + + PHP, + ['ignored_tags' => ['todo']], + ), + new CodeSample( + <<<'PHP' + $sqlite) { + $sqlite->open($path); + } + + function returnClassName() { + /** @var class-string */ + return \StdClass::class; + } + + PHP, + ['allow_before_return_statement' => true], + ), + ], + ); + } + + protected function configurePostNormalisation(): void + { + $this->ignoredTags = array_map( + static fn (string $tag): string => strtolower($tag), + $this->configuration['ignored_tags'], + ); + + $this->allowBeforeReturnStatement = true === $this->configuration['allow_before_return_statement']; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('ignored_tags', 'List of ignored tags (matched case insensitively).')) + ->setAllowedTypes(['string[]']) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('allow_before_return_statement', 'Whether to allow PHPDoc before return statement.')) + ->setAllowedTypes(['bool']) + ->setDefault(Future::getV4OrV3(true, false)) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $commentsAnalyzer = new CommentsAnalyzer(); + + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { + continue; + } + + if ($this->allowBeforeReturnStatement && $commentsAnalyzer->isBeforeReturn($tokens, $index)) { + continue; + } + + if ($commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { + continue; + } + + if (0 < Preg::matchAll('~\@([a-zA-Z0-9_\\\-]+)\b~', $token->getContent(), $matches)) { + foreach ($matches[1] as $match) { + if (\in_array(strtolower($match), $this->ignoredTags, true)) { + continue 2; + } + } + } + + $tokens[$index] = new Token([\T_COMMENT, '/*'.ltrim($token->getContent(), '/*')]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php new file mode 100644 index 0000000..2a18cc0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php @@ -0,0 +1,195 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\DocBlock\ShortDescription; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Nobu Funaki + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTrimConsecutiveBlankLineSeparationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra blank lines after summary and after description in PHPDoc.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $summaryEnd = (new ShortDescription($doc))->getEnd(); + + if (null !== $summaryEnd) { + $this->fixSummary($doc, $summaryEnd); + $this->fixDescription($doc, $summaryEnd); + } + + $this->fixAllTheRest($doc); + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + private function fixSummary(DocBlock $doc, int $summaryEnd): void + { + $nonBlankLineAfterSummary = $this->findNonBlankLine($doc, $summaryEnd); + + $this->removeExtraBlankLinesBetween($doc, $summaryEnd, $nonBlankLineAfterSummary); + } + + private function fixDescription(DocBlock $doc, int $summaryEnd): void + { + $annotationStart = $this->findFirstAnnotationOrEnd($doc); + + // assuming the end of the Description appears before the first Annotation + $descriptionEnd = $this->reverseFindLastUsefulContent($doc, $annotationStart); + + if (null === $descriptionEnd || $summaryEnd === $descriptionEnd) { + return; // no Description + } + + if ($annotationStart === \count($doc->getLines()) - 1) { + return; // no content after Description + } + + $this->removeExtraBlankLinesBetween($doc, $descriptionEnd, $annotationStart); + } + + private function fixAllTheRest(DocBlock $doc): void + { + $annotationStart = $this->findFirstAnnotationOrEnd($doc); + $lastLine = $this->reverseFindLastUsefulContent($doc, \count($doc->getLines()) - 1); + + if (null !== $lastLine && $annotationStart !== $lastLine) { + $this->removeExtraBlankLinesBetween($doc, $annotationStart, $lastLine); + } + } + + private function removeExtraBlankLinesBetween(DocBlock $doc, int $from, int $to): void + { + for ($index = $from + 1; $index < $to; ++$index) { + $line = $doc->getLine($index); + $next = $doc->getLine($index + 1); + $this->removeExtraBlankLine($line, $next); + } + } + + private function removeExtraBlankLine(Line $current, Line $next): void + { + if (!$current->isTheEnd() && !$current->containsUsefulContent() + && !$next->isTheEnd() && !$next->containsUsefulContent()) { + $current->remove(); + } + } + + private function findNonBlankLine(DocBlock $doc, int $after): ?int + { + foreach ($doc->getLines() as $index => $line) { + if ($index <= $after) { + continue; + } + + if ($line->containsATag() || $line->containsUsefulContent() || $line->isTheEnd()) { + return $index; + } + } + + return null; + } + + private function findFirstAnnotationOrEnd(DocBlock $doc): int + { + foreach ($doc->getLines() as $index => $line) { + if ($line->containsATag()) { + return $index; + } + } + + if (!isset($index)) { + throw new \LogicException('PHPDoc has empty lines collection.'); + } + + return $index; // no Annotation, return the last line + } + + private function reverseFindLastUsefulContent(DocBlock $doc, int $from): ?int + { + for ($index = $from - 1; $index >= 0; --$index) { + if ($doc->getLine($index)->containsUsefulContent()) { + return $index; + } + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php new file mode 100644 index 0000000..8532a42 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTrimFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'PHPDoc should start and end with content, excluding the very first and last line of the docblocks.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $content = $token->getContent(); + $content = $this->fixStart($content); + // we need re-parse the docblock after fixing the start before + // fixing the end in order for the lines to be correctly indexed + $content = $this->fixEnd($content); + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + + /** + * Make sure the first useful line starts immediately after the first line. + */ + private function fixStart(string $content): string + { + return Preg::replace( + '~ + (^/\*\*) # DocComment begin + (?: + \R\h*(?:\*\h*)? # lines without useful content + (?!\R\h*\*/) # not followed by a DocComment end + )+ + (\R\h*(?:\*\h*)?\S) # first line with useful content + ~x', + '$1$2', + $content, + ); + } + + /** + * Make sure the last useful line is immediately before the final line. + */ + private function fixEnd(string $content): string + { + return Preg::replace( + '~ + (\R\h*(?:\*\h*)?\S.*?) # last line with useful content + (?: + (? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * exclude?: list<'$this'|'array'|'bool'|'boolean'|'callable'|'double'|'false'|'float'|'int'|'integer'|'iterable'|'mixed'|'null'|'object'|'parent'|'resource'|'scalar'|'self'|'static'|'string'|'true'|'void'>, + * groups?: list<'alias'|'meta'|'simple'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * exclude: list<'$this'|'array'|'bool'|'boolean'|'callable'|'double'|'false'|'float'|'int'|'integer'|'iterable'|'mixed'|'null'|'object'|'parent'|'resource'|'scalar'|'self'|'static'|'string'|'true'|'void'>, + * groups: list<'alias'|'meta'|'simple'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * Available types, grouped. + * + * @var non-empty-array> + */ + private const POSSIBLE_TYPES = [ + 'alias' => [ + 'boolean', + 'double', + 'integer', + ], + 'meta' => [ + '$this', + 'false', + 'mixed', + 'parent', + 'resource', + 'scalar', + 'self', + 'static', + 'true', + 'void', + ], + 'simple' => [ + 'array', + 'bool', + 'callable', + 'float', + 'int', + 'iterable', + 'null', + 'object', + 'string', + ], + ]; + + /** @var array */ + private array $typesSetToFix; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'The correct case must be used for standard PHP types in PHPDoc.', + [ + new CodeSample( + <<<'PHP' + ['simple', 'alias']], + ), + new CodeSample( + <<<'PHP' + ['resource']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoDuplicateTypesFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesNoDuplicatesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocIndentFixer. + */ + public function getPriority(): int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run before + * the phpdoc_scalar_fixer so that it can make changes after us. + */ + return 16; + } + + protected function configurePostNormalisation(): void + { + $typesToFix = array_merge(...array_map(static fn (string $group): array => self::POSSIBLE_TYPES[$group], $this->configuration['groups'])); + $this->typesSetToFix = array_combine($typesToFix, array_fill(0, \count($typesToFix), true)); + + foreach ($this->configuration['exclude'] as $type) { + unset($this->typesSetToFix[$type]); + } + } + + protected function normalize(string $type): string + { + $typeExpression = new TypeExpression($type, null, []); + + $newTypeExpression = $typeExpression->mapTypes(function (TypeExpression $type) { + if ($type->isUnionType()) { + return $type; + } + + $value = $type->toString(); + $valueLower = strtolower($value); + if (isset($this->typesSetToFix[$valueLower])) { + return new TypeExpression($valueLower, null, []); + } + + return $type; + }); + + return $newTypeExpression->toString(); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $possibleGroups = array_keys(self::POSSIBLE_TYPES); + $allPossibleTypes = array_merge(...array_values(self::POSSIBLE_TYPES)); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('exclude', 'List of types to exclude from fixing, regardless of groups.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($allPossibleTypes)]) + ->setDefault([]) + ->getOption(), + (new FixerOptionBuilder('groups', 'Type groups to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($possibleGroups)]) + ->setDefault($possibleGroups) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesNoDuplicatesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesNoDuplicatesFixer.php new file mode 100644 index 0000000..e2dc432 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesNoDuplicatesFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @deprecated in favour of PhpdocNoDuplicateTypesFixer + */ +final class PhpdocTypesNoDuplicatesFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes duplicate PHPDoc types.', + [ + new CodeSample( + <<<'PHP' + createProxyFixers()[0]->getPriority(); + } + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + protected function createProxyFixers(): array + { + $fixer = new PhpdocNoDuplicateTypesFixer(); + + return [$fixer]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php new file mode 100644 index 0000000..8561ae4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php @@ -0,0 +1,234 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * case_sensitive?: bool, + * null_adjustment?: 'always_first'|'always_last'|'none', + * sort_algorithm?: 'alpha'|'none', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * case_sensitive: bool, + * null_adjustment: 'always_first'|'always_last'|'none', + * sort_algorithm: 'alpha'|'none', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocTypesOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Sorts PHPDoc types.', + [ + new CodeSample( + <<<'PHP' + 'always_last'], + ), + new CodeSample( + <<<'PHP' + 'alpha'], + ), + new CodeSample( + <<<'PHP' + 'alpha', + 'null_adjustment' => 'always_last', + ], + ), + new CodeSample( + <<<'PHP' + 'alpha', + 'null_adjustment' => 'none', + ], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocListTypeFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('sort_algorithm', 'The sorting algorithm to apply.')) + ->setAllowedValues(['alpha', 'none']) + ->setDefault('alpha') + ->getOption(), + (new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).')) + ->setAllowedValues(['always_first', 'always_last', 'none']) + ->setDefault('always_first') + ->getOption(), + (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES); + + if (0 === \count($annotations)) { + continue; + } + + foreach ($annotations as $annotation) { + // fix main types + if (null !== $annotation->getTypeExpression()) { + $annotation->setTypes( + $this->sortTypes( + $annotation->getTypeExpression(), + ), + ); + } + + // fix @method parameters types + $line = $doc->getLine($annotation->getStart()); + $line->setContent(Preg::replaceCallback('/\*\h*@method\h+'.TypeExpression::REGEX_TYPES.'\h+\K(?&callable)/', function (array $matches): string { + \assert(isset($matches[0])); + + $typeExpression = new TypeExpression($matches[0], null, []); + + return implode('|', $this->sortTypes($typeExpression)); + }, $line->getContent())); + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + /** + * @return list + */ + private function sortTypes(TypeExpression $typeExpression): array + { + $normalizeType = static fn (string $type): string => Preg::replace('/^\(*\??\\\?/', '', $type); + + $sortedTypeExpression = $typeExpression->sortTypes( + function (TypeExpression $a, TypeExpression $b) use ($normalizeType): int { + $a = $normalizeType($a->toString()); + $b = $normalizeType($b->toString()); + $lowerCaseA = strtolower($a); + $lowerCaseB = strtolower($b); + + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + + if ('alpha' === $this->configuration['sort_algorithm']) { + return true === $this->configuration['case_sensitive'] ? $a <=> $b : strcasecmp($a, $b); + } + + return 0; + }, + ); + + return $sortedTypeExpression->getTypes(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php new file mode 100644 index 0000000..734e2d7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocVarAnnotationCorrectOrderFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@var` and `@type` annotations must have type and name in the correct order.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + if (!str_contains(strtolower($token->getContent()), strtolower('@var')) && !str_contains(strtolower($token->getContent()), strtolower('@type'))) { + continue; + } + + $newContent = Preg::replace( + '/(@(?:type|var)\s*)(\$\S+)(\h+)([^\$](?:[^<\s]|<[^>]*>)*)(\s|\*)/i', + '$1$4$3$2$5', + $token->getContent(), + ); + + if ($newContent === $token->getContent()) { + continue; + } + + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php new file mode 100644 index 0000000..0342302 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * @author Dave van der Brugge + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpdocVarWithoutNameFixer extends AbstractFixer +{ + private const PROPERTY_MODIFIER_KINDS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + '`@var` and `@type` annotations of classy properties should not contain the name.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $nextIndex) { + continue; + } + + // For people writing "static public $foo" instead of "public static $foo" + if ($tokens[$nextIndex]->isGivenKind(\T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + + // We want only doc blocks that are for properties and thus have specified access modifiers next + if (!$tokens[$nextIndex]->isGivenKind(self::PROPERTY_MODIFIER_KINDS)) { + continue; + } + + $doc = new DocBlock($token->getContent()); + + $firstLevelLines = $this->getFirstLevelLines($doc); + $annotations = $doc->getAnnotationsOfType(['type', 'var']); + + foreach ($annotations as $annotation) { + if (isset($firstLevelLines[$annotation->getStart()])) { + $this->fixLine($firstLevelLines[$annotation->getStart()]); + } + } + + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + + private function fixLine(Line $line): void + { + Preg::matchAll('/ \$'.TypeExpression::REGEX_IDENTIFIER.'(?getContent(), $matches); + + foreach ($matches[0] as $match) { + $line->setContent(str_replace($match, '', $line->getContent())); + } + } + + /** + * @return array + */ + private function getFirstLevelLines(DocBlock $docBlock): array + { + $nested = 0; + $lines = $docBlock->getLines(); + + foreach ($lines as $index => $line) { + $content = $line->getContent(); + + if (Preg::match('/\s*\*\s*}$/', $content)) { + --$nested; + } + + if ($nested > 0) { + unset($lines[$index]); + } + + if (Preg::match('/\s\{$/', $content)) { + ++$nested; + } + } + + return $lines; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php new file mode 100644 index 0000000..5df1425 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoUselessReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be an empty `return` statement at the end of a function.', + [ + new CodeSample( + <<<'PHP' + $token) { + if (!$token->isGivenKind(\T_FUNCTION)) { + continue; + } + + $index = $tokens->getNextTokenOfKind($index, [';', '{']); + if ($tokens[$index]->equals('{')) { + $this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index)); + } + } + } + + /** + * @param int $start Token index of the opening brace token of the function + * @param int $end Token index of the closing brace token of the function + */ + private function fixFunction(Tokens $tokens, int $start, int $end): void + { + for ($index = $end; $index > $start; --$index) { + if (!$tokens[$index]->isGivenKind(\T_RETURN)) { + continue; + } + + $nextAt = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$nextAt]->equals(';')) { + continue; + } + + if ($tokens->getNextMeaningfulToken($nextAt) !== $end) { + continue; + } + + $previous = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$previous]->equalsAny([[\T_ELSE], ')'])) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($nextAt); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php new file mode 100644 index 0000000..1d832bf --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php @@ -0,0 +1,638 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * skip_named_var_tags?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * skip_named_var_tags: bool, + * } + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + */ +final class ReturnAssignmentFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Local, dynamic and directly referenced variables should not be assigned and directly returned by a function or method.', + [ + new CodeSample( + <<<'PHP' + true, + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer. + * Must run after NoEmptyStatementFixer, NoUnneededBracesFixer, NoUnneededCurlyBracesFixer. + */ + public function getPriority(): int + { + return -15; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN, \T_VARIABLE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = \count($tokens); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + + for ($index = 1; $index < $tokenCount; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $next = $tokens->getNextMeaningfulToken($index); + if ($tokens[$next]->isGivenKind(CT::T_RETURN_REF)) { + continue; + } + + $functionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$functionOpenIndex]->equals(';')) { // abstract function + $index = $functionOpenIndex - 1; + + continue; + } + + $functionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $functionOpenIndex); + $totalTokensAdded = 0; + + do { + $tokensAdded = $this->fixFunction( + $tokens, + $index, + $functionOpenIndex, + $functionCloseIndex, + ); + + $functionCloseIndex += $tokensAdded; + $totalTokensAdded += $tokensAdded; + } while ($tokensAdded > 0); + + $index = $functionCloseIndex; + $tokenCount += $totalTokensAdded; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('skip_named_var_tags', 'Whether to skip cases where named `@var` tags are used.')) + ->setDefault(false) + ->setAllowedTypes(['bool']) + ->getOption(), + ]); + } + + /** + * @param int $functionIndex token index of T_FUNCTION + * @param int $functionOpenIndex token index of the opening brace token of the function + * @param int $functionCloseIndex token index of the closing brace token of the function + * + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function fixFunction(Tokens $tokens, int $functionIndex, int $functionOpenIndex, int $functionCloseIndex): int + { + $inserted = 0; + $candidates = []; + $isRisky = false; + + if ($tokens[$tokens->getNextMeaningfulToken($functionIndex)]->isGivenKind(CT::T_RETURN_REF)) { + $isRisky = true; + } + + // go through the function declaration and check if references are passed + // - check if it will be risky to fix return statements of this function + for ($index = $functionIndex + 1; $index < $functionOpenIndex; ++$index) { + if ($tokens[$index]->equals('&')) { + $isRisky = true; + + break; + } + } + + // go through all the tokens of the body of the function: + // - check if it will be risky to fix return statements of this function + // - check nested functions; fix when found and update the upper limit + number of inserted token + // - check for return statements that might be fixed (based on if fixing will be risky, which is only know after analyzing the whole function) + + for ($index = $functionOpenIndex + 1; $index < $functionCloseIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $nestedFunctionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$nestedFunctionOpenIndex]->equals(';')) { // abstract function + $index = $nestedFunctionOpenIndex - 1; + + continue; + } + + $nestedFunctionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $nestedFunctionOpenIndex); + + $tokensAdded = $this->fixFunction( + $tokens, + $index, + $nestedFunctionOpenIndex, + $nestedFunctionCloseIndex, + ); + + $index = $nestedFunctionCloseIndex + $tokensAdded; + $functionCloseIndex += $tokensAdded; + $inserted += $tokensAdded; + } + + if ($isRisky) { + continue; // don't bother to look into anything else than nested functions as the current is risky already + } + + if ($tokens[$index]->equals('&')) { + $isRisky = true; + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_RETURN)) { + $candidates[] = $index; + + continue; + } + + // test if there is anything in the function body that might + // change global state or indirect changes (like through references, eval, etc.) + + if ($tokens[$index]->isGivenKind([ + CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case + \T_EVAL, // "$c = eval('return $this;');" case + \T_GLOBAL, + \T_INCLUDE, // loading additional symbols we cannot analyse here + \T_INCLUDE_ONCE, // " + \T_REQUIRE, // " + \T_REQUIRE_ONCE, // " + ])) { + $isRisky = true; + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$nextIndex]->isGivenKind(\T_FUNCTION)) { + $isRisky = true; // "static $a" case + + continue; + } + } + + if ($tokens[$index]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + $isRisky = true; // "$$a" case + + continue; + } + } + + if ($this->tokensAnalyzer->isSuperGlobal($index)) { + $isRisky = true; + + continue; + } + } + + if ($isRisky) { + return $inserted; + } + + // fix the candidates in reverse order when applicable + for ($i = \count($candidates) - 1; $i >= 0; --$i) { + \assert(isset($candidates[$i])); + $index = $candidates[$i]; + + // Check if returning only a variable (i.e. not the result of an expression, function call etc.) + $returnVarIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$returnVarIndex]->isGivenKind(\T_VARIABLE)) { + continue; // example: "return 1;" + } + + $endReturnVarIndex = $tokens->getNextMeaningfulToken($returnVarIndex); + if (!$tokens[$endReturnVarIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + continue; // example: "return $a + 1;" + } + + // Check that the variable is assigned just before it is returned + $assignVarEndIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$assignVarEndIndex]->equals(';')) { + continue; // example: "? return $a;" + } + + // Note: here we are @ "; return $a;" (or "; return $a ? >") + while (true) { + $prevMeaningful = $tokens->getPrevMeaningfulToken($assignVarEndIndex); + + if (!$tokens[$prevMeaningful]->equals(')')) { + break; + } + + $assignVarEndIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $prevMeaningful); + } + + $assignVarOperatorIndex = $tokens->getPrevTokenOfKind( + $assignVarEndIndex, + ['=', ';', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]], + ); + + if ($tokens[$assignVarOperatorIndex]->equals('}')) { + $startIndex = $this->isCloseBracePartOfDefinition($tokens, $assignVarOperatorIndex); // test for `anonymous class`, `lambda` and `match` + + if (null === $startIndex) { + continue; + } + + $assignVarOperatorIndex = $tokens->getPrevMeaningfulToken($startIndex); + } + + if (!$tokens[$assignVarOperatorIndex]->equals('=')) { + continue; + } + + // Note: here we are @ "= [^;{] ; return $a;" + $assignVarIndex = $tokens->getPrevMeaningfulToken($assignVarOperatorIndex); + if (!$tokens[$assignVarIndex]->equals($tokens[$returnVarIndex], false)) { + continue; + } + + // Note: here we are @ "$a = [^;{] ; return $a;" + $beforeAssignVarIndex = $tokens->getPrevMeaningfulToken($assignVarIndex); + if (!$tokens[$beforeAssignVarIndex]->equalsAny([';', '{', '}'])) { + continue; + } + + if ( + $this->configuration['skip_named_var_tags'] + && $this->hasNamedVarTag($tokens, $assignVarIndex, $functionOpenIndex) + ) { + continue; + } + + // Check if there is a `catch` or `finally` block between the assignment and the return + if ($this->isUsedInCatchOrFinally($tokens, $returnVarIndex, $functionOpenIndex, $functionCloseIndex)) { + continue; + } + + // Note: here we are @ "[;{}] $a = [^;{] ; return $a;" + $inserted += $this->simplifyReturnStatement( + $tokens, + $assignVarIndex, + $assignVarOperatorIndex, + $index, + $endReturnVarIndex, + ); + } + + return $inserted; + } + + /** + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function simplifyReturnStatement( + Tokens $tokens, + int $assignVarIndex, + int $assignVarOperatorIndex, + int $returnIndex, + int $returnVarEndIndex + ): int { + $inserted = 0; + $originalIndent = $tokens[$assignVarIndex - 1]->isWhitespace() + ? $tokens[$assignVarIndex - 1]->getContent() + : null; + + // remove the return statement + if ($tokens[$returnVarEndIndex]->equals(';')) { // do not remove PHP close tags + $tokens->clearTokenAndMergeSurroundingWhitespace($returnVarEndIndex); + } + + for ($i = $returnIndex; $i <= $returnVarEndIndex - 1; ++$i) { + $this->clearIfSave($tokens, $i); + } + + // remove no longer needed indentation of the old/remove return statement + if ($tokens[$returnIndex - 1]->isWhitespace()) { + $content = $tokens[$returnIndex - 1]->getContent(); + $fistLinebreakPos = strrpos($content, "\n"); + $content = false === $fistLinebreakPos + ? ' ' + : substr($content, $fistLinebreakPos); + + $tokens[$returnIndex - 1] = new Token([\T_WHITESPACE, $content]); + } + + // remove the variable and the assignment + for ($i = $assignVarIndex; $i <= $assignVarOperatorIndex; ++$i) { + $this->clearIfSave($tokens, $i); + } + + // insert new return statement + $tokens->insertAt($assignVarIndex, new Token([\T_RETURN, 'return'])); + ++$inserted; + + // use the original indent of the var assignment for the new return statement + if ( + null !== $originalIndent + && $tokens[$assignVarIndex - 1]->isWhitespace() + && $originalIndent !== $tokens[$assignVarIndex - 1]->getContent() + ) { + $tokens[$assignVarIndex - 1] = new Token([\T_WHITESPACE, $originalIndent]); + } + + // remove trailing space after the new return statement which might be added during the cleanup process + $nextIndex = $tokens->getNonEmptySibling($assignVarIndex, 1); + if (!$tokens[$nextIndex]->isWhitespace()) { + $tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, ' '])); + ++$inserted; + } + + return $inserted; + } + + private function clearIfSave(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isComment()) { + return; + } + + if ($tokens[$index]->isWhitespace() && $tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + return; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + /** + * @param int $index open brace index + * + * @return null|int index of the first token of a definition (lambda, anonymous class or match) or `null` if not an anonymous + */ + private function isCloseBracePartOfDefinition(Tokens $tokens, int $index): ?int + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $index); + $candidateIndex = $this->isOpenBraceOfLambda($tokens, $index); + + if (null !== $candidateIndex) { + return $candidateIndex; + } + + $candidateIndex = $this->isOpenBraceOfAnonymousClass($tokens, $index); + + return $candidateIndex ?? $this->isOpenBraceOfMatch($tokens, $index); + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_NEW of anonymous class or `null` if not an anonymous + */ + private function isOpenBraceOfAnonymousClass(Tokens $tokens, int $index): ?int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($tokens[$index]->equalsAny([',', [\T_STRING], [\T_IMPLEMENTS], [\T_EXTENDS], [\T_NS_SEPARATOR]])); + + if ($tokens[$index]->equals(')')) { // skip constructor braces and content within + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->tokensAnalyzer->isAnonymousClass($index)) { + return null; + } + + return $tokens->getPrevTokenOfKind($index, [[\T_NEW]]); + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_FUNCTION or T_STATIC of lambda or `null` if not a lambda + */ + private function isOpenBraceOfLambda(Tokens $tokens, int $index): ?int + { + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->equals(')')) { + return null; + } + + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { + $index = $tokens->getPrevTokenOfKind($index, [')']); + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + return null; + } + + $staticCandidate = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$staticCandidate]->isGivenKind(\T_STATIC) ? $staticCandidate : $index; + } + + /** + * @param int $index open brace index + * + * @return null|int index of T_MATCH or `null` if not a `match` + */ + private function isOpenBraceOfMatch(Tokens $tokens, int $index): ?int + { + if (!$tokens->isTokenKindFound(FCT::T_MATCH)) { + return null; + } + + $index = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$index]->equals(')')) { + return null; + } + + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getPrevMeaningfulToken($index); + + return $tokens[$index]->isGivenKind(\T_MATCH) ? $index : null; + } + + private function hasNamedVarTag(Tokens $tokens, int $assignVarIndex, int $functionOpenIndex): bool + { + $docIndex = $tokens->getPrevTokenOfKind($assignVarIndex, [[\T_DOC_COMMENT]]); + if (null === $docIndex || $docIndex <= $functionOpenIndex) { + return false; + } + + $doc = new DocBlock($tokens[$docIndex]->getContent()); + $annotations = $doc->getAnnotationsOfType(['var', 'psalm-var', 'phpstan-var']); + + foreach ($annotations as $annotation) { + if (null !== $annotation->getVariableName()) { + return true; + } + } + + return false; + } + + private function isUsedInCatchOrFinally(Tokens $tokens, int $returnVarIndex, int $functionOpenIndex, int $functionCloseIndex): bool + { + // Find try + $tryIndex = $tokens->getPrevTokenOfKind($returnVarIndex, [[\T_TRY]]); + if (null === $tryIndex || $tryIndex <= $functionOpenIndex) { + return false; + } + $tryOpenIndex = $tokens->getNextTokenOfKind($tryIndex, ['{']); + $tryCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $tryOpenIndex); + + // Find catch or finally + $nextIndex = $tokens->getNextMeaningfulToken($tryCloseIndex); + if (null === $nextIndex) { + return false; + } + + // Find catches + while ($tokens[$nextIndex]->isGivenKind(\T_CATCH)) { + $catchOpenIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']); + $catchCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $catchOpenIndex); + + if ($catchCloseIndex >= $functionCloseIndex) { + return false; + } + $varIndex = $tokens->getNextTokenOfKind($catchOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $catchCloseIndex) { + return true; + } + + $nextIndex = $tokens->getNextMeaningfulToken($catchCloseIndex); + if (null === $nextIndex) { + return false; + } + } + + if (!$tokens[$nextIndex]->isGivenKind(\T_FINALLY)) { + return false; + } + + $finallyIndex = $nextIndex; + if ($finallyIndex >= $functionCloseIndex) { + return false; + } + $finallyOpenIndex = $tokens->getNextTokenOfKind($finallyIndex, ['{']); + $finallyCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $finallyOpenIndex); + $varIndex = $tokens->getNextTokenOfKind($finallyOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $finallyCloseIndex) { + return true; + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php new file mode 100644 index 0000000..0ec50df --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php @@ -0,0 +1,198 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SimplifiedNullReturnFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A return statement wishing to return `void` should not return `null`.', + [ + new CodeSample("isTokenKindFound(\T_RETURN); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->fixRange($tokens, 1, $tokens->count() - 1); + } + + private function fixRange(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + if ($tokens[$index]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $propertyHookCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $index); + $this->scanRange($tokens, $index, $propertyHookCloseIndex); + $index = $propertyHookCloseIndex; + + continue; + } + + if (!$tokens[$index]->isGivenKind(\T_RETURN)) { + continue; + } + + if ($this->needFixing($tokens, $index)) { + $this->clear($tokens, $index); + } + } + } + + private function scanRange(Tokens $tokens, int $startIndex, int $endIndex): void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $braceOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $braceOpenIndex); + $this->fixRange($tokens, $braceOpenIndex, $braceCloseIndex); + $index = $braceCloseIndex; + } + } + } + + /** + * Clear the return statement located at a given index. + */ + private function clear(Tokens $tokens, int $index): void + { + while (!$tokens[++$index]->equalsAny([';', [\T_CLOSE_TAG]])) { + if ($this->shouldClearToken($tokens, $index)) { + $tokens->clearAt($index); + } + } + } + + /** + * Does the return statement located at a given index need fixing? + */ + private function needFixing(Tokens $tokens, int $index): bool + { + if ($this->isStrictOrNullableReturnTypeFunction($tokens, $index)) { + return false; + } + + $content = ''; + while (!$tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) { + $index = $tokens->getNextMeaningfulToken($index); + $content .= $tokens[$index]->getContent(); + } + + $lastTokenContent = $tokens[$index]->getContent(); + $content = substr($content, 0, -\strlen($lastTokenContent)); + + $content = ltrim($content, '('); + $content = rtrim($content, ')'); + + return 'null' === strtolower($content); + } + + /** + * Is the return within a function with a non-void or nullable return type? + * + * @param int $returnIndex Current return token index + */ + private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, int $returnIndex): bool + { + $functionIndex = $returnIndex; + do { + $functionIndex = $tokens->getPrevTokenOfKind($functionIndex, [[\T_FUNCTION]]); + if (null === $functionIndex) { + return false; + } + $openingCurlyBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['{']); + $closingCurlyBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $openingCurlyBraceIndex); + } while ($closingCurlyBraceIndex < $returnIndex); + + $possibleVoidIndex = $tokens->getPrevMeaningfulToken($openingCurlyBraceIndex); + $isStrictReturnType = $tokens[$possibleVoidIndex]->isGivenKind([\T_STRING, CT::T_ARRAY_TYPEHINT]) + && 'void' !== $tokens[$possibleVoidIndex]->getContent(); + + $nullableTypeIndex = $tokens->getNextTokenOfKind($functionIndex, [[CT::T_NULLABLE_TYPE]]); + $isNullableReturnType = null !== $nullableTypeIndex && $nullableTypeIndex < $openingCurlyBraceIndex; + + return $isStrictReturnType || $isNullableReturnType; + } + + /** + * Should we clear the specific token? + * + * We'll leave it alone if + * - token is a comment + * - token is whitespace that is immediately before a comment + * - token is whitespace that is immediately before the PHP close tag + * - token is whitespace that is immediately after a comment and before a semicolon + */ + private function shouldClearToken(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if ($token->isComment()) { + return false; + } + + if (!$token->isWhitespace()) { + return true; + } + + if ( + $tokens[$index + 1]->isComment() + || $tokens[$index + 1]->isGivenKind(\T_CLOSE_TAG) + || ($tokens[$index - 1]->isComment() && $tokens[$index + 1]->equals(';')) + ) { + return false; + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 0000000..cacb59f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,256 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * strategy?: 'new_line_for_chained_calls'|'no_multi_line', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * strategy: 'new_line_for_chained_calls'|'no_multi_line', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Graham Campbell + * @author Egidijus Girčys + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @internal + */ + public const STRATEGY_NO_MULTI_LINE = 'no_multi_line'; + + /** + * @internal + */ + public const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.', + [ + new CodeSample( + <<<'PHP' + method1() + ->method2() + ->method(3); + + PHP, + ['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before SpaceAfterSemicolonFixer. + * Must run after CombineConsecutiveIssetsFixer, GetClassToClassKeywordFixer, NoEmptyStatementFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'strategy', + 'Forbid multi-line whitespace or move the semicolon to the new line for chained calls.', + )) + ->setAllowedValues([self::STRATEGY_NO_MULTI_LINE, self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS]) + ->setDefault(self::STRATEGY_NO_MULTI_LINE) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind(\T_CONST)) { + $index = $tokens->getNextTokenOfKind($index, [';']); + + continue; + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + $previousIndex = $index - 1; + $previous = $tokens[$previousIndex]; + + $indent = $this->findWhitespaceBeforeFirstCall($index, $tokens); + if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy'] && null !== $indent) { + if ($previous->isWhitespace() && $previous->getContent() === $lineEnding.$indent) { + continue; + } + + // unset whitespace and semicolon + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + $tokens->clearAt($index); + + // find the line ending token index after the semicolon + $index = $this->getNewLineIndex($index, $tokens); + + // appended new line to the last method call + $newline = new Token([\T_WHITESPACE, $lineEnding.$indent]); + + // insert the new line with indented semicolon + $tokens->insertAt($index++, [$newline, new Token(';')]); + } else { + if (!$previous->isWhitespace() || !str_contains($previous->getContent(), "\n")) { + continue; + } + + $content = $previous->getContent(); + if (str_starts_with($content, $lineEnding) && $tokens[$index - 2]->isComment()) { + // if there is comment between closing parenthesis and semicolon + + // unset whitespace and semicolon + $tokens->clearAt($previousIndex); + $tokens->clearAt($index); + + // find the significant token index before the semicolon + $significantTokenIndex = $this->getPreviousSignificantTokenIndex($index, $tokens); + + // insert the semicolon + $tokens->insertAt($significantTokenIndex + 1, [new Token(';')]); + } else { + // if there is whitespace between closing bracket and semicolon, just remove it + $tokens->clearAt($previousIndex); + } + } + } + } + + /** + * Find the index for the next new line. Return the given index when there's no new line. + */ + private function getNewLineIndex(int $index, Tokens $tokens): int + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) { + break; + } + if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) { + return $index; + } + } + + return $index; + } + + /** + * Find the index for the previous significant token. Return the given index when there's no significant token. + */ + private function getPreviousSignificantTokenIndex(int $index, Tokens $tokens): int + { + $stopTokens = [ + \T_LNUMBER, + \T_DNUMBER, + \T_STRING, + \T_VARIABLE, + \T_CONSTANT_ENCAPSED_STRING, + ]; + for ($index; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($stopTokens) || $tokens[$index]->equals(')')) { + return $index; + } + } + + return $index; + } + + /** + * Checks if the semicolon closes a multiline call and returns the whitespace of the first call at $index. + * i.e. it will return the whitespace marked with '____' in the example underneath. + * + * .. + * ____$this->methodCall() + * ->anotherCall(); + * .. + */ + private function findWhitespaceBeforeFirstCall(int $index, Tokens $tokens): ?string + { + $isMultilineCall = false; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + while (!$tokens[$prevIndex]->equalsAny([';', ':', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_ELSE]])) { + $index = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null !== $blockType && !$blockType['isStart']) { + $prevIndex = $tokens->findBlockStart($blockType['type'], $index); + + continue; + } + + if ($tokens[$index]->isObjectOperator() || $tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $isMultilineCall = $isMultilineCall || $tokens->isPartialCodeMultiline($prevIndex, $index); + } + } + + return $isMultilineCall ? WhitespacesAnalyzer::detectIndent($tokens, $index) : null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php new file mode 100644 index 0000000..91197ef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php @@ -0,0 +1,188 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoEmptyStatementFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove useless (semicolon) statements.', + [ + new CodeSample("isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind([\T_BREAK, \T_CONTINUE])) { + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals([\T_LNUMBER, '1'])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + continue; + } + + // skip T_FOR parenthesis to ignore double `;` like `for ($i = 1; ; ++$i) {...}` + if ($tokens[$index]->isGivenKind(\T_FOR)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $tokens->getNextMeaningfulToken($index)) + 1; + + continue; + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($index); + + // A semicolon can always be removed if it follows a semicolon, '{' or opening tag. + if ($tokens[$previousMeaningfulIndex]->equalsAny(['{', ';', [\T_OPEN_TAG]])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + continue; + } + + // A semicolon might be removed if it follows a '}' but only if the brace is part of certain structures. + if ($tokens[$previousMeaningfulIndex]->equals('}')) { + $this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex); + + continue; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_CLOSE)) { + continue; + } + + // A semicolon might be removed together with its noop statement, for example "getPrevMeaningfulToken($previousMeaningfulIndex); + + if ( + $tokens[$prePreviousMeaningfulIndex]->equalsAny([';', '{', '}', [\T_OPEN_TAG]]) + && $tokens[$previousMeaningfulIndex]->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_DNUMBER, \T_LNUMBER, \T_STRING, \T_VARIABLE]) + ) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($previousMeaningfulIndex); + } + } + } + + /** + * Fix semicolon after closing curly brace if needed. + * + * Test for the following cases + * - just '{' '}' block (following open tag or ';') + * - if, else, elseif + * - interface, trait, class (but not anonymous) + * - catch, finally (but not try) + * - for, foreach, while (but not 'do - while') + * - switch + * - function (declaration, but not lambda) + * - declare (with '{' '}') + * - namespace (with '{' '}') + * + * @param int $index Semicolon index + */ + private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, int $index, int $curlyCloseIndex): void + { + $curlyOpeningIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $curlyCloseIndex); + $beforeCurlyOpeningIndex = $tokens->getPrevMeaningfulToken($curlyOpeningIndex); + + if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind([\T_ELSE, \T_FINALLY, \T_NAMESPACE, \T_OPEN_TAG]) || $tokens[$beforeCurlyOpeningIndex]->equalsAny([';', '{', '}'])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + return; + } + + // check for namespaces and class, interface and trait definitions + if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind(\T_STRING)) { + $classyTestIndex = $tokens->getPrevMeaningfulToken($beforeCurlyOpeningIndex); + + while ($tokens[$classyTestIndex]->equals(',') || $tokens[$classyTestIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR, \T_EXTENDS, \T_IMPLEMENTS])) { + $classyTestIndex = $tokens->getPrevMeaningfulToken($classyTestIndex); + } + + $tokensAnalyzer = new TokensAnalyzer($tokens); + + if ( + $tokens[$classyTestIndex]->isGivenKind(\T_NAMESPACE) + || ($tokens[$classyTestIndex]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTestIndex)) + ) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + return; + } + + // early return check, below only control structures with conditions are fixed + if (!$tokens[$beforeCurlyOpeningIndex]->equals(')')) { + return; + } + + $openingBraceIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $beforeCurlyOpeningIndex); + $beforeOpeningBraceIndex = $tokens->getPrevMeaningfulToken($openingBraceIndex); + + if ($tokens[$beforeOpeningBraceIndex]->isGivenKind([\T_IF, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE, \T_SWITCH, \T_CATCH, \T_DECLARE])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + + return; + } + + // check for function definition + if ($tokens[$beforeOpeningBraceIndex]->isGivenKind(\T_STRING)) { + $beforeStringIndex = $tokens->getPrevMeaningfulToken($beforeOpeningBraceIndex); + + if ($tokens[$beforeStringIndex]->isGivenKind(\T_FUNCTION)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); // implicit return + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 0000000..d3f584b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Graham Campbell + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSinglelineWhitespaceBeforeSemicolonsFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Single-line whitespace before closing semicolon are prohibited.', + [new CodeSample("foo() ;\n")], + ); + } + + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveIssetsFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, NoEmptyStatementFixer, NoUnneededImportAliasFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(" \t")) { + continue; + } + + if ($tokens[$index - 2]->equals(';')) { + // do not remove all whitespace before the semicolon because it is also whitespace after another semicolon + $tokens->ensureWhitespaceAtIndex($index - 1, 0, ' '); + } elseif (!$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php new file mode 100644 index 0000000..5c08880 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SemicolonAfterInstructionFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Instructions must be terminated with a semicolon.', + [new CodeSample("\n")], + ); + } + + /** + * {@inheritdoc} + * + * Must run before SimplifiedIfReturnFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_CLOSE_TAG); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; $index > 1; --$index) { + if (!$tokens[$index]->isGivenKind(\T_CLOSE_TAG)) { + continue; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prev]->equalsAny([';', '{', '}', ':', [\T_OPEN_TAG]])) { + continue; + } + + $tokens->insertAt($prev + 1, new Token(';')); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php new file mode 100644 index 0000000..259e934 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php @@ -0,0 +1,161 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * remove_in_empty_for_expressions?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * remove_in_empty_for_expressions: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SpaceAfterSemicolonFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Fix whitespace after a semicolon.', + [ + new CodeSample( + <<<'PHP' + true, + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveUnsetsFixer, MultilineWhitespaceBeforeSemicolonsFixer, NoEmptyStatementFixer, OrderedClassElementsFixer, SingleImportPerStatementFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority(): int + { + return -1; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(';'); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('remove_in_empty_for_expressions', 'Whether spaces should be removed for empty `for` expressions.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $insideForParenthesesUntil = null; + + for ($index = 0, $max = \count($tokens) - 1; $index < $max; ++$index) { + if (true === $this->configuration['remove_in_empty_for_expressions']) { + if ($tokens[$index]->isGivenKind(\T_FOR)) { + $index = $tokens->getNextMeaningfulToken($index); + $insideForParenthesesUntil = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($index === $insideForParenthesesUntil) { + $insideForParenthesesUntil = null; + + continue; + } + } + + if (!$tokens[$index]->equals(';')) { + continue; + } + + if (!$tokens[$index + 1]->isWhitespace()) { + if ( + !$tokens[$index + 1]->equalsAny([')', [\T_INLINE_HTML]]) && ( + false === $this->configuration['remove_in_empty_for_expressions'] + || !$tokens[$index + 1]->equals(';') + ) + ) { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + ++$max; + } + + continue; + } + + if ( + null !== $insideForParenthesesUntil + && ($tokens[$index + 2]->equals(';') || $index + 2 === $insideForParenthesesUntil) + && !Preg::match('/\R/', $tokens[$index + 1]->getContent()) + ) { + $tokens->clearAt($index + 1); + + continue; + } + + if ( + isset($tokens[$index + 2]) + && !$tokens[$index + 1]->equals([\T_WHITESPACE, ' ']) + && $tokens[$index + 1]->isWhitespace(" \t") + && !$tokens[$index + 2]->isComment() + && !$tokens[$index + 2]->equals(')') + ) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php new file mode 100644 index 0000000..799084e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php @@ -0,0 +1,333 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use Symfony\Component\OptionsResolver\Options; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * preserve_existing_declaration?: bool, + * strategy?: 'add_when_missing'|'enforce'|'remove', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * strategy: 'add_when_missing'|'enforce'|'remove', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Jordi Boggiano + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DeclareStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Force a strict types mode in all files.', + [ + new CodeSample( + " 'enforce'], + ), + new CodeSample( + " 'add_when_missing'], + ), + new CodeSample( + " 'remove'], + ), + new CodeSample( + " 'remove'], + ), + new CodeSample( // @TODO v4.0: remove me, "preserve_existing_declaration" option is deprecated + " false], + ), + new CodeSample( // @TODO v4.0: remove me, "preserve_existing_declaration" option is deprecated + " true], + ), + ], + null, + 'Enabling strict types will stop non strict code from working.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineAfterOpeningTagFixer, DeclareEqualNormalizeFixer, HeaderCommentFixer. + */ + public function getPriority(): int + { + return 2; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO); + } + + public function isRisky(): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $fixerName = $this->getName(); + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('preserve_existing_declaration', 'Whether existing strict_types=? should be preserved and not overridden.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->setNormalizer(static function (Options $options, bool $value) use ($fixerName): bool { + if (true === $value && 'enforce' !== $options['strategy']) { + throw new InvalidFixerConfigurationException( + $fixerName, + 'Cannot configure "strategy" in parallel to configuring "preserve_existing_declaration".', + ); + } + + return $value; + }) + ->setDeprecationMessage('Use `strategy` to configure behaviour.') // @TODO 4.0: remove option and normalizer related to it + ->getOption(), + (new FixerOptionBuilder('strategy', 'Whether existing strict_types=? should be enforced, removed (effectively turning strict mode off and using the engine into default type coercion mode), or added when missing.')) + ->setAllowedValues(['remove', 'add_when_missing', 'enforce']) + ->setDefault('enforce') + ->getOption(), + ]); + } + + /** + * @TODO v4.0: remove the hook + */ + protected function configurePostNormalisation(): void + { + // @phpstan-ignore-next-line offsetAccess.notFound "preserve_existing_declaration" option is deprecated + if ('enforce' === $this->configuration['strategy'] && true === $this->configuration['preserve_existing_declaration']) { + $this->configuration['strategy'] = 'add_when_missing'; + } + + // @phpstan-ignore-next-line unset.offset "preserve_existing_declaration" option is deprecated + unset($this->configuration['preserve_existing_declaration']); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0; + + $declaration = $this->getStrictTypesDeclaration($tokens); + + if ('remove' === $this->configuration['strategy']) { + if (null !== $declaration) { + $this->removeStrictTypesDeclaration($tokens, $declaration); + } + + return; + } + + if (null === $declaration) { + $this->insertSequence($openTagIndex, $tokens); // declaration not found, insert one + + return; + } + + $this->fixStrictTypesCasingAndValue($tokens, $declaration['sequence']); + } + + /** + * @return null|array{declare_index: int, open_parenthesis: int, close_parenthesis: int, sequence: array} + */ + private function getStrictTypesDeclaration(Tokens $tokens): ?array + { + foreach ($tokens->findGivenKind(\T_DECLARE) as $index => $token) { + $openParenthesis = $tokens->getNextMeaningfulToken($index); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis); + + $strictTypesSequence = $tokens->findSequence([[\T_STRING, 'strict_types'], '=', [\T_LNUMBER]], $openParenthesis, $closeParenthesis, false); + if (null === $strictTypesSequence) { + continue; + } + + return [ + 'declare_index' => $index, + 'open_parenthesis' => $openParenthesis, + 'close_parenthesis' => $closeParenthesis, + 'sequence' => $strictTypesSequence, + ]; + } + + return null; + } + + /** + * @param array{declare_index: int, open_parenthesis: int, close_parenthesis: int, sequence: array} $declaration + */ + private function removeStrictTypesDeclaration(Tokens $tokens, array $declaration): void + { + $sequenceIndices = array_keys($declaration['sequence']); + $sequenceIndexMap = array_fill_keys($sequenceIndices, true); + \assert(\array_key_exists(0, $sequenceIndices)); + $sequenceStart = $sequenceIndices[0]; + $sequenceEnd = $sequenceIndices[\count($sequenceIndices) - 1]; + + if (!$this->hasOtherDeclareOptions($tokens, $declaration['open_parenthesis'], $declaration['close_parenthesis'], $sequenceIndexMap)) { + $this->removeDeclareStatement($tokens, $declaration['declare_index'], $declaration['close_parenthesis']); + + return; + } + + for ($index = $sequenceEnd; $index >= $sequenceStart; --$index) { + if ($tokens->isEmptyAt($index)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + + $prevMeaningful = $tokens->getPrevMeaningfulToken($sequenceStart); + if (null !== $prevMeaningful && $tokens[$prevMeaningful]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningful); + + $nextMeaningful = $tokens->getNextMeaningfulToken($sequenceEnd); + if (null !== $nextMeaningful) { + $tokens->removeLeadingWhitespace($nextMeaningful, " \t"); + } + + return; + } + + $nextMeaningful = $tokens->getNextMeaningfulToken($sequenceEnd); + if (null !== $nextMeaningful && $tokens[$nextMeaningful]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($nextMeaningful); + + $afterComma = $tokens->getNextMeaningfulToken($nextMeaningful); + if (null !== $afterComma) { + $tokens->removeLeadingWhitespace($afterComma, " \t"); + } + } + } + + /** + * @param array $sequenceIndexMap + */ + private function hasOtherDeclareOptions(Tokens $tokens, int $openParenthesis, int $closeParenthesis, array $sequenceIndexMap): bool + { + $index = $tokens->getNextMeaningfulToken($openParenthesis); + while (null !== $index && $index < $closeParenthesis) { + if ($tokens[$index]->isGivenKind(\T_STRING) && !isset($sequenceIndexMap[$index])) { + return true; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return false; + } + + private function removeDeclareStatement(Tokens $tokens, int $declareIndex, int $closeParenthesis): void + { + $semicolonIndex = $tokens->getNextMeaningfulToken($closeParenthesis); + if (null === $semicolonIndex) { + return; + } + + for ($index = $semicolonIndex; $index >= $declareIndex; --$index) { + if ($tokens->isEmptyAt($index)) { + continue; + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + + /** + * @param array $sequence + */ + private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence): void + { + foreach ($sequence as $index => $token) { + if ($token->isGivenKind(\T_STRING)) { + $tokens[$index] = new Token([\T_STRING, strtolower($token->getContent())]); + + continue; + } + + if ($token->isGivenKind(\T_LNUMBER) && 'enforce' === $this->configuration['strategy']) { + $tokens[$index] = new Token([\T_LNUMBER, '1']); + + break; + } + } + } + + private function insertSequence(int $openTagIndex, Tokens $tokens): void + { + $sequence = [ + new Token([\T_DECLARE, 'declare']), + new Token('('), + new Token([\T_STRING, 'strict_types']), + new Token('='), + new Token([\T_LNUMBER, '1']), + new Token(')'), + new Token(';'), + ]; + $nextIndex = $openTagIndex + \count($sequence) + 1; + + $tokens->insertAt($openTagIndex + 1, $sequence); + + // transform "getContent(); + if (!str_contains($content, ' ') || str_contains($content, "\n")) { + $tokens[$openTagIndex] = new Token([$tokens[$openTagIndex]->getId(), trim($tokens[$openTagIndex]->getContent()).' ']); + } + + if (\count($tokens) === $nextIndex) { + return; // no more tokens after sequence, single_blank_line_at_eof might add a line + } + + $lineEnding = $this->whitespacesConfig->getLineEnding(); + if ($tokens[$nextIndex]->isWhitespace()) { + $content = $tokens[$nextIndex]->getContent(); + $tokens[$nextIndex] = new Token([\T_WHITESPACE, $lineEnding.ltrim($content, " \t")]); + } else { + $tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, $lineEnding])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php new file mode 100644 index 0000000..eae5b37 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StrictComparisonFixer extends AbstractFixer +{ + private const FIX_MAP = [ + \T_IS_EQUAL => [\T_IS_IDENTICAL, '==='], + \T_IS_NOT_EQUAL => [\T_IS_NOT_IDENTICAL, '!=='], + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Comparisons should be strict.', + [new CodeSample("isAnyTokenKindsFound([\T_IS_EQUAL, \T_IS_NOT_EQUAL]); + } + + public function isRisky(): bool + { + return true; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens->findGivenKind([\T_IS_EQUAL, \T_IS_NOT_EQUAL]) as $kind => $kindTokens) { + foreach ($kindTokens as $index => $token) { + \assert(isset(self::FIX_MAP[$kind])); + $newToken = self::FIX_MAP[$kind]; + + $tokens[$index] = new Token($newToken); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php new file mode 100644 index 0000000..65212d3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php @@ -0,0 +1,170 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StrictParamFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Functions should be used with `$strict` param set to `true`.', + [new CodeSample("isTokenKindFound(\T_STRING); + } + + public function isRisky(): bool + { + return true; + } + + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionInvocationFixer. + */ + public function getPriority(): int + { + return 31; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + static $map = null; + + if (null === $map) { + $trueToken = new Token([\T_STRING, 'true']); + + $map = [ + 'array_keys' => [null, null, $trueToken], + 'array_search' => [null, null, $trueToken], + 'base64_decode' => [null, $trueToken], + 'in_array' => [null, null, $trueToken], + 'mb_detect_encoding' => [null, [new Token([\T_STRING, 'mb_detect_order']), new Token('('), new Token(')')], $trueToken], + ]; + } + + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + + $nextIndex = $tokens->getNextMeaningfulToken($index); + if (null !== $nextIndex && !$tokens[$nextIndex]->equals('(')) { + continue; + } + + $lowercaseContent = strtolower($token->getContent()); + if (isset($map[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $this->fixFunction($tokens, $index, $map[$lowercaseContent]); + } + } + } + + /** + * @param list $functionParams + */ + private function fixFunction(Tokens $tokens, int $functionIndex, array $functionParams): void + { + $startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['(']); + $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $startBraceIndex); + $paramsQuantity = 0; + $expectParam = true; + + for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) { + $token = $tokens[$index]; + + if ($expectParam && !$token->isWhitespace() && !$token->isComment()) { + ++$paramsQuantity; + $expectParam = false; + } + + if ($token->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $index); + + continue; + } + + if ($token->equals(',')) { + $expectParam = true; + + continue; + } + } + + $functionParamsQuantity = \count($functionParams); + + if ($paramsQuantity === $functionParamsQuantity) { + return; + } + + $tokensToInsert = []; + + for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) { + // function call do not have all params that are required to set useStrict flag, exit from method! + if (null === $functionParams[$i]) { + return; + } + + $tokensToInsert[] = new Token(','); + $tokensToInsert[] = new Token([\T_WHITESPACE, ' ']); + + if (!\is_array($functionParams[$i])) { + $tokensToInsert[] = clone $functionParams[$i]; + + continue; + } + + foreach ($functionParams[$i] as $param) { + $tokensToInsert[] = clone $param; + } + } + + $beforeEndBraceIndex = $tokens->getPrevMeaningfulToken($endBraceIndex); + + if ($tokens[$beforeEndBraceIndex]->equals(',')) { + array_shift($tokensToInsert); + $tokensToInsert[] = new Token(','); + } + + $tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php new file mode 100644 index 0000000..24162f5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @deprecated Use `string_implicit_backslashes` with config: ['single_quoted' => 'ignore', 'double_quoted' => 'escape', 'heredoc' => 'escape'] (default) + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * double_quoted?: bool, + * heredoc_syntax?: bool, + * single_quoted?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * double_quoted: bool, + * heredoc_syntax: bool, + * single_quoted: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * @author Michael Vorisek + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EscapeImplicitBackslashesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getSuccessorsNames(): array + { + return array_keys($this->proxyFixers); + } + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'EOF' + true], + ), + new CodeSample( + $codeSample, + ['double_quoted' => false], + ), + new CodeSample( + $codeSample, + ['heredoc_syntax' => false], + ), + ], + 'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash ' + .'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain ' + .'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes ' + ."that do not start a special interpretation with the char after them.\n" + .'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash ' + .'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted ' + .'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocToNowdocFixer, SingleQuoteFixer. + * Must run after MultilineStringToHeredocFixer. + */ + public function getPriority(): int + { + return parent::getPriority(); + } + + protected function configurePostNormalisation(): void + { + /** @var StringImplicitBackslashesFixer */ + $stringImplicitBackslashesFixer = $this->proxyFixers['string_implicit_backslashes']; + + $stringImplicitBackslashesFixer->configure([ + 'single_quoted' => true === $this->configuration['single_quoted'] ? 'escape' : 'ignore', + 'double_quoted' => true === $this->configuration['double_quoted'] ? 'escape' : 'ignore', + 'heredoc' => true === $this->configuration['heredoc_syntax'] ? 'escape' : 'ignore', + ]); + } + + protected function createProxyFixers(): array + { + $stringImplicitBackslashesFixer = new StringImplicitBackslashesFixer(); + $stringImplicitBackslashesFixer->configure([ + 'single_quoted' => 'ignore', + 'double_quoted' => 'escape', + 'heredoc' => 'escape', + ]); + + return [ + $stringImplicitBackslashesFixer, + ]; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('single_quoted', 'Whether to fix single-quoted strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + (new FixerOptionBuilder('double_quoted', 'Whether to fix double-quoted strings.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + (new FixerOptionBuilder('heredoc_syntax', 'Whether to fix heredoc syntax.')) + ->setAllowedTypes(['bool']) + ->setDefault(true) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php new file mode 100644 index 0000000..6908e7d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php @@ -0,0 +1,168 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Filippo Tessarotto + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ExplicitStringVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax.', + [new CodeSample( + <<<'EOT' + country !"; + $c = "I have $farm[0] chickens !"; + + EOT, + )], + 'The reasoning behind this rule is the following:' + ."\n".'- When there are two valid ways of doing the same thing, using both is confusing, there should be a coding standard to follow.' + ."\n".'- PHP manual marks `"$var"` syntax as implicit and `"{$var}"` syntax as explicit: explicit code should always be preferred.' + ."\n".'- Explicit syntax allows word concatenation inside strings, e.g. `"{$var}IsAVar"`, implicit doesn\'t.' + ."\n".'- Explicit syntax is easier to detect for IDE/editors and therefore has colors/highlight with higher contrast, which is easier to read.' + ."\n".'Backtick operator is skipped because it is harder to handle; you can use `backtick_to_shell_exec` fixer to normalize backticks to strings.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessConcatOperatorFixer. + * Must run after BacktickToShellExecFixer. + */ + public function getPriority(): int + { + return 6; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_VARIABLE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $backtickStarted = false; + for ($index = \count($tokens) - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if ($token->equals('`')) { + $backtickStarted = !$backtickStarted; + + continue; + } + + if ($backtickStarted || !$token->isGivenKind(\T_VARIABLE)) { + continue; + } + + $prevToken = $tokens[$index - 1]; + + if (!$this->isStringPartToken($prevToken)) { + continue; + } + + $distinctVariableIndex = $index; + $variableTokens = [ + $distinctVariableIndex => [ + 'tokens' => [$index => $token], + 'firstVariableTokenIndex' => $index, + 'lastVariableTokenIndex' => $index, + ], + ]; + + $nextIndex = $index + 1; + $squareBracketCount = 0; + + while (!$this->isStringPartToken($tokens[$nextIndex])) { + if ($tokens[$nextIndex]->isGivenKind(\T_CURLY_OPEN)) { + $nextIndex = $tokens->getNextTokenOfKind($nextIndex, [[CT::T_CURLY_CLOSE]]); + } elseif ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE) && 1 !== $squareBracketCount) { + $distinctVariableIndex = $nextIndex; + $variableTokens[$distinctVariableIndex] = [ + 'tokens' => [$nextIndex => $tokens[$nextIndex]], + 'firstVariableTokenIndex' => $nextIndex, + 'lastVariableTokenIndex' => $nextIndex, + ]; + } else { + $variableTokens[$distinctVariableIndex]['tokens'][$nextIndex] = $tokens[$nextIndex]; + $variableTokens[$distinctVariableIndex]['lastVariableTokenIndex'] = $nextIndex; + + if ($tokens[$nextIndex]->equalsAny(['[', ']'])) { + ++$squareBracketCount; + } + } + + ++$nextIndex; + } + krsort($variableTokens, \SORT_NUMERIC); + + foreach ($variableTokens as $distinctVariableSet) { + if (1 === \count($distinctVariableSet['tokens'])) { + $singleVariableIndex = array_key_first($distinctVariableSet['tokens']); + $singleVariableToken = current($distinctVariableSet['tokens']); + $tokens->overrideRange($singleVariableIndex, $singleVariableIndex, [ + new Token([\T_CURLY_OPEN, '{']), + new Token([\T_VARIABLE, $singleVariableToken->getContent()]), + new Token([CT::T_CURLY_CLOSE, '}']), + ]); + } else { + foreach ($distinctVariableSet['tokens'] as $variablePartIndex => $variablePartToken) { + if ($variablePartToken->isGivenKind(\T_NUM_STRING)) { + $tokens[$variablePartIndex] = new Token([\T_LNUMBER, $variablePartToken->getContent()]); + + continue; + } + + if ($variablePartToken->isGivenKind(\T_STRING) && $tokens[$variablePartIndex + 1]->equals(']')) { + $tokens[$variablePartIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "'".$variablePartToken->getContent()."'"]); + } + } + + $tokens->insertAt($distinctVariableSet['lastVariableTokenIndex'] + 1, new Token([CT::T_CURLY_CLOSE, '}'])); + $tokens->insertAt($distinctVariableSet['firstVariableTokenIndex'], new Token([\T_CURLY_OPEN, '{'])); + } + } + } + } + + /** + * Check if token is a part of a string. + * + * @param Token $token The token to check + */ + private function isStringPartToken(Token $token): bool + { + return $token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) + || $token->isGivenKind(\T_START_HEREDOC) + || '"' === $token->getContent() + || 'b"' === strtolower($token->getContent()); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocClosingMarkerFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocClosingMarkerFixer.php new file mode 100644 index 0000000..760d042 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocClosingMarkerFixer.php @@ -0,0 +1,207 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * closing_marker?: string, + * explicit_heredoc_style?: bool, + * reserved_closing_markers?: list, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * closing_marker: string, + * explicit_heredoc_style: bool, + * reserved_closing_markers: list, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Michael Vorisek + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class HeredocClosingMarkerFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var non-empty-list + */ + public const RESERVED_CLOSING_MARKERS = [ + 'CSS', + 'DIFF', + 'HTML', + 'JS', + 'JSON', + 'MD', + 'PHP', + 'PYTHON', + 'RST', + 'TS', + 'SQL', + 'XML', + 'YAML', + ]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Unify `heredoc` or `nowdoc` closing marker.', + [ + new CodeSample( + <<<'EOD' + 'EOF'], + ), + new CodeSample( + <<<'EOD_' + true], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_START_HEREDOC); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder( + 'closing_marker', + 'Preferred closing marker.', + )) + ->setAllowedTypes(['string']) + ->setDefault('EOD') + ->getOption(), + (new FixerOptionBuilder( + 'reserved_closing_markers', + 'Reserved closing markers to be kept unchanged.', + )) + ->setAllowedTypes(['string[]']) + ->setDefault(self::RESERVED_CLOSING_MARKERS) + ->getOption(), + (new FixerOptionBuilder( + 'explicit_heredoc_style', + 'Whether the closing marker should be wrapped in double quotes.', + )) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $reservedClosingMarkersMap = null; + + $startIndex = null; + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_START_HEREDOC)) { + $startIndex = $index; + + continue; + } + + if (null !== $startIndex && $token->isGivenKind(\T_END_HEREDOC)) { + $existingClosingMarker = trim($token->getContent()); + + if (null === $reservedClosingMarkersMap) { + $reservedClosingMarkersMap = []; + foreach ($this->configuration['reserved_closing_markers'] as $v) { + $reservedClosingMarkersMap[mb_strtoupper($v)] = $v; + } + } + + $existingClosingMarker = mb_strtoupper($existingClosingMarker); + do { + $newClosingMarker = $reservedClosingMarkersMap[$existingClosingMarker] ?? null; + if (!str_ends_with($existingClosingMarker, '_')) { + break; + } + $existingClosingMarker = substr($existingClosingMarker, 0, -1); + } while (null === $newClosingMarker); + + if (null === $newClosingMarker) { + $newClosingMarker = $this->configuration['closing_marker']; + } + + $content = $tokens->generatePartialCode($startIndex + 1, $index - 1); + while (Preg::match('~(^|[\r\n])\s*'.preg_quote($newClosingMarker, '~').'(?!\w)~', $content)) { + $newClosingMarker .= '_'; + } + + [$tokens[$startIndex], $tokens[$index]] = $this->convertClosingMarker($tokens[$startIndex], $token, $newClosingMarker); + + $startIndex = null; + + continue; + } + } + } + + /** + * @return array{Token, Token} + */ + private function convertClosingMarker(Token $startToken, Token $endToken, string $newClosingMarker): array + { + $isNowdoc = str_contains($startToken->getContent(), '\''); + + $markerQuote = $isNowdoc + ? '\'' + : (true === $this->configuration['explicit_heredoc_style'] ? '"' : ''); + + return [new Token([ + $startToken->getId(), + Preg::replace('/<<<\h*\K["\']?[^\s"\']+["\']?/', $markerQuote.$newClosingMarker.$markerQuote, $startToken->getContent()), + ]), new Token([ + $endToken->getId(), + Preg::replace('/\S+/', $newClosingMarker, $endToken->getContent()), + ])]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php new file mode 100644 index 0000000..7bbbd86 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php @@ -0,0 +1,109 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class HeredocToNowdocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Convert `heredoc` to `nowdoc` where possible.', + [ + new CodeSample( + <<<'EOF' + isTokenKindFound(\T_START_HEREDOC); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_START_HEREDOC) || str_contains($token->getContent(), "'")) { + continue; + } + + if ($tokens[$index + 1]->isGivenKind(\T_END_HEREDOC)) { + $tokens[$index] = $this->convertToNowdoc($token); + + continue; + } + + if ( + !$tokens[$index + 1]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) + || !$tokens[$index + 2]->isGivenKind(\T_END_HEREDOC) + ) { + continue; + } + + $content = $tokens[$index + 1]->getContent(); + // regex: odd number of backslashes, not followed by dollar + if (Preg::match('/(?convertToNowdoc($token); + $content = str_replace(['\\\\', '\$'], ['\\', '$'], $content); + $tokens[$index + 1] = new Token([ + $tokens[$index + 1]->getId(), + $content, + ]); + } + } + + /** + * Transforms the heredoc start token to nowdoc notation. + */ + private function convertToNowdoc(Token $token): Token + { + return new Token([ + $token->getId(), + Preg::replace('/^([Bb]?<<<)(\h*)"?([^\s"]+)"?/', '$1$2\'$3\'', $token->getContent()), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/MultilineStringToHeredocFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/MultilineStringToHeredocFixer.php new file mode 100644 index 0000000..8dbc68e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/MultilineStringToHeredocFixer.php @@ -0,0 +1,156 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Michael Vorisek + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MultilineStringToHeredocFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Convert multiline string to `heredoc` or `nowdoc`.', + [ + new CodeSample( + <<<'EOD' + getName()}"; + EOD."\n", + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE]); + } + + /** + * {@inheritdoc} + * + * Must run before EscapeImplicitBackslashesFixer, HeredocIndentationFixer, StringImplicitBackslashesFixer. + */ + public function getPriority(): int + { + return 16; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $complexStringStartIndex = null; + foreach ($tokens as $index => $token) { + if (null === $complexStringStartIndex) { + if ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $this->convertStringToHeredoc($tokens, $index, $index); + } elseif ($token->equalsAny(['"', 'b"', 'B"'])) { + $complexStringStartIndex = $index; + } + } elseif ($token->equals('"')) { + $this->convertStringToHeredoc($tokens, $complexStringStartIndex, $index); + + $complexStringStartIndex = null; + } + } + } + + private function convertStringToHeredoc(Tokens $tokens, int $stringStartIndex, int $stringEndIndex): void + { + $closingMarker = 'EOD'; + + if ($tokens[$stringStartIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $content = $tokens[$stringStartIndex]->getContent(); + if ('b' === strtolower(substr($content, 0, 1))) { + $content = substr($content, 1); + } + $isSingleQuoted = str_starts_with($content, '\''); + $content = substr($content, 1, -1); + + if ($isSingleQuoted) { + $content = Preg::replace('~\\\([\\\\\'])~', '$1', $content); + } else { + $content = Preg::replace('~(\\\\\\\)|\\\(")~', '$1$2', $content); + } + + $constantStringToken = new Token([\T_ENCAPSED_AND_WHITESPACE, $content."\n"]); + } else { + $content = $tokens->generatePartialCode($stringStartIndex + 1, $stringEndIndex - 1); + $isSingleQuoted = false; + $constantStringToken = null; + } + + if (!str_contains($content, "\n") && !str_contains($content, "\r")) { + return; + } + + while (Preg::match('~(^|[\r\n])\s*'.preg_quote($closingMarker, '~').'(?!\w)~', $content)) { + $closingMarker .= '_'; + } + + $quoting = $isSingleQuoted ? '\'' : ''; + $heredocStartToken = new Token([\T_START_HEREDOC, '<<<'.$quoting.$closingMarker.$quoting."\n"]); + $heredocEndToken = new Token([\T_END_HEREDOC, $closingMarker]); + + if (null !== $constantStringToken) { + $tokens->overrideRange($stringStartIndex, $stringEndIndex, [ + $heredocStartToken, + $constantStringToken, + $heredocEndToken, + ]); + } else { + for ($i = $stringStartIndex + 1; $i < $stringEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + $tokens[$i] = new Token([ + $tokens[$i]->getId(), + Preg::replace('~(\\\\\\\)|\\\(")~', '$1$2', $tokens[$i]->getContent()), + ]); + } + } + + $tokens[$stringStartIndex] = $heredocStartToken; + $tokens[$stringEndIndex] = $heredocEndToken; + if ($tokens[$stringEndIndex - 1]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + $tokens[$stringEndIndex - 1] = new Token([ + $tokens[$stringEndIndex - 1]->getId(), + $tokens[$stringEndIndex - 1]->getContent()."\n", + ]); + } else { + $tokens->insertAt($stringEndIndex, new Token([ + \T_ENCAPSED_AND_WHITESPACE, + "\n", + ])); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php new file mode 100644 index 0000000..a0c1e04 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author ntzm + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoBinaryStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound( + [ + \T_CONSTANT_ENCAPSED_STRING, + \T_START_HEREDOC, + 'b"', + ], + ); + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There should not be a binary flag before strings.', + [ + new CodeSample(" $token) { + if ($token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_START_HEREDOC])) { + $content = $token->getContent(); + + if ('b' === strtolower($content[0])) { + $tokens[$index] = new Token([$token->getId(), substr($content, 1)]); + } + } elseif ($token->equals('b"')) { + $tokens[$index] = new Token('"'); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php new file mode 100644 index 0000000..96d08dc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingWhitespaceInStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no trailing whitespace at the end of lines in strings.', + [ + new CodeSample( + "count() - 1, $last = true; $index >= 0; --$index, $last = false) { + $token = $tokens[$index]; + + if (!$token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML])) { + continue; + } + + $isInlineHtml = $token->isGivenKind(\T_INLINE_HTML); + $regex = $isInlineHtml && $last ? '/\h+(?=\R|$)/' : '/\h+(?=\R)/'; + $content = Preg::replace($regex, '', $token->getContent()); + + if ($token->getContent() === $content) { + continue; + } + + if (!$isInlineHtml || 0 === $index) { + $this->updateContent($tokens, $index, $content); + + continue; + } + + $prev = $index - 1; + + if ($tokens[$prev]->equals([\T_CLOSE_TAG, '?>']) && Preg::match('/^\R/', $content, $match)) { + $tokens[$prev] = new Token([\T_CLOSE_TAG, $tokens[$prev]->getContent().$match[0]]); + $content = substr($content, \strlen($match[0])); + $content = false === $content ? '' : $content; // @phpstan-ignore-line due to https://github.com/phpstan/phpstan/issues/1215 , awaiting PHP8 as min requirement of Fixer + } + + $this->updateContent($tokens, $index, $content); + } + } + + private function updateContent(Tokens $tokens, int $index, string $content): void + { + if ('' === $content) { + $tokens->clearAt($index); + + return; + } + + $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php new file mode 100644 index 0000000..3cbdc5d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dave van der Brugge + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SimpleToComplexStringVariableFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Converts explicit variables in double-quoted strings and heredoc syntax from simple to complex format (`${` to `{$`).', + [ + new CodeSample( + <<<'EOT' + isTokenKindFound(\T_DOLLAR_OPEN_CURLY_BRACES); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 3; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_DOLLAR_OPEN_CURLY_BRACES)) { + continue; + } + $varnameToken = $tokens[$index + 1]; + + if (!$varnameToken->isGivenKind(\T_STRING_VARNAME)) { + continue; + } + + $dollarCloseToken = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_COMPLEX_STRING_VARIABLE, $index); + + $prevTokenContent = $tokens[$index - 1]->getContent(); + if (str_ends_with($prevTokenContent, '$') && !str_ends_with($prevTokenContent, '\$')) { + $tokens[$index - 1] = new Token([\T_ENCAPSED_AND_WHITESPACE, substr($prevTokenContent, 0, -1).'\$']); + } + $tokens[$index] = new Token([\T_CURLY_OPEN, '{']); + $tokens[$index + 1] = new Token([\T_VARIABLE, '$'.$varnameToken->getContent()]); + $tokens[$dollarCloseToken] = new Token([CT::T_CURLY_CLOSE, '}']); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php new file mode 100644 index 0000000..48d7fb6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * strings_containing_single_quote_chars?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * strings_containing_single_quote_chars: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleQuoteFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'EOF' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before NoUselessConcatOperatorFixer. + * Must run after BacktickToShellExecFixer, EscapeImplicitBackslashesFixer, StringImplicitBackslashesFixer. + */ + public function getPriority(): int + { + return 10; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_CONSTANT_ENCAPSED_STRING); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + + $content = $token->getContent(); + $prefix = ''; + + if ('b' === strtolower($content[0])) { + $prefix = $content[0]; + $content = substr($content, 1); + } + + if ( + '"' === $content[0] + && (true === $this->configuration['strings_containing_single_quote_chars'] || !str_contains($content, "'")) + // regex: odd number of backslashes, not followed by double quote or dollar + && !Preg::match('/(?setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringImplicitBackslashesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringImplicitBackslashesFixer.php new file mode 100644 index 0000000..0f25ff9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringImplicitBackslashesFixer.php @@ -0,0 +1,195 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * double_quoted?: 'escape'|'ignore'|'unescape', + * heredoc?: 'escape'|'ignore'|'unescape', + * single_quoted?: 'escape'|'ignore'|'unescape', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * double_quoted: 'escape'|'ignore'|'unescape', + * heredoc: 'escape'|'ignore'|'unescape', + * single_quoted: 'escape'|'ignore'|'unescape', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Filippo Tessarotto + * @author Michael Vorisek + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StringImplicitBackslashesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + $codeSample = <<<'EOF' + 'escape'], + ), + new CodeSample( + $codeSample, + ['double_quoted' => 'unescape'], + ), + new CodeSample( + $codeSample, + ['heredoc' => 'unescape'], + ), + ], + 'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash ' + .'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain ' + .'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes ' + ."that do not start a special interpretation with the char after them.\n" + .'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash ' + .'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted ' + .'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.', + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING]); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocToNowdocFixer, SingleQuoteFixer. + * Must run after MultilineStringToHeredocFixer. + */ + public function getPriority(): int + { + return 15; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $singleQuotedReservedRegex = '[\'\\\]'; + $doubleQuotedReservedRegex = '(?:[efnrtv$"\\\0-7]|x[0-9A-Fa-f]|u{|$)'; + $heredocSyntaxReservedRegex = '(?:[efnrtv$\\\0-7]|x[0-9A-Fa-f]|u{|$)'; + + $doubleQuoteOpened = false; + foreach ($tokens as $index => $token) { + if ($token->equalsAny(['"', 'b"', 'B"'])) { + $doubleQuoteOpened = !$doubleQuoteOpened; + } + + if (!$token->isGivenKind([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING])) { + continue; + } + + $content = $token->getContent(); + if (!str_contains($content, '\\')) { + continue; + } + + // nowdoc syntax + if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) && '\'' === substr(rtrim($tokens[$index - 1]->getContent()), -1)) { + continue; + } + + $firstTwoCharacters = strtolower(substr($content, 0, 2)); + $isSingleQuotedString = $token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) && ('\'' === $content[0] || 'b\'' === $firstTwoCharacters); + $isDoubleQuotedString = ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) && ('"' === $content[0] || 'b"' === $firstTwoCharacters)) + || ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) && $doubleQuoteOpened); + + if ($isSingleQuotedString + ? 'ignore' === $this->configuration['single_quoted'] + : ($isDoubleQuotedString + ? 'ignore' === $this->configuration['double_quoted'] + : 'ignore' === $this->configuration['heredoc']) + ) { + continue; + } + + $escapeBackslashes = $isSingleQuotedString + ? 'escape' === $this->configuration['single_quoted'] + : ($isDoubleQuotedString + ? 'escape' === $this->configuration['double_quoted'] + : 'escape' === $this->configuration['heredoc']); + + $reservedRegex = $isSingleQuotedString + ? $singleQuotedReservedRegex + : ($isDoubleQuotedString + ? $doubleQuotedReservedRegex + : $heredocSyntaxReservedRegex); + + if ($escapeBackslashes) { + $regex = '/(?getId(), $newContent]); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('single_quoted', 'Whether to escape backslashes in single-quoted strings.')) + ->setAllowedValues(['escape', 'unescape', 'ignore']) + ->setDefault('unescape') + ->getOption(), + (new FixerOptionBuilder('double_quoted', 'Whether to escape backslashes in double-quoted strings.')) + ->setAllowedValues(['escape', 'unescape', 'ignore']) + ->setDefault('escape') + ->getOption(), + (new FixerOptionBuilder('heredoc', 'Whether to escape backslashes in heredoc syntax.')) + ->setAllowedValues(['escape', 'unescape', 'ignore']) + ->setDefault('escape') + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php new file mode 100644 index 0000000..d51b121 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php @@ -0,0 +1,326 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StringLengthToEmptyFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'String tests for empty must be done against `\'\'`, not with `strlen`.', + [new CodeSample("findStrLengthCalls($tokens) as $candidate) { + [$functionNameIndex, $openParenthesisIndex, $closeParenthesisIndex] = $candidate; + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex); + + if (1 !== \count($arguments)) { + continue; // must be one argument + } + + // test for leading `\` before `strlen` call + + $nextIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + + if ($tokens[$previousIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $namespaceSeparatorIndex = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + } else { + $namespaceSeparatorIndex = null; + } + + // test for yoda vs non-yoda fix case + + if ($this->isOperatorOfInterest($tokens[$previousIndex])) { // test if valid yoda case to fix + $operatorIndex = $previousIndex; + $operandIndex = $tokens->getPrevMeaningfulToken($previousIndex); + + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1` + continue; + } + + $replacement = $this->getReplacementYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + + if (null === $replacement) { + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$nextIndex])) { // is of higher precedence right; continue + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$tokens->getPrevMeaningfulToken($operandIndex)])) { // is of higher precedence left; continue + continue; + } + } elseif ($this->isOperatorOfInterest($tokens[$nextIndex])) { // test if valid !yoda case to fix + $operatorIndex = $nextIndex; + $operandIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1` + continue; + } + + $replacement = $this->getReplacementNotYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + + if (null === $replacement) { + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$tokens->getNextMeaningfulToken($operandIndex)])) { // is of higher precedence right; continue + continue; + } + + if ($this->isOfHigherPrecedence($tokens[$previousIndex])) { // is of higher precedence left; continue + continue; + } + } else { + continue; + } + + // prepare for fixing + + $keepParentheses = $this->keepParentheses($tokens, $openParenthesisIndex, $closeParenthesisIndex); + + if (\T_IS_IDENTICAL === $replacement) { + $operandContent = '==='; + } else { // T_IS_NOT_IDENTICAL === $replacement + $operandContent = '!=='; + } + + // apply fixing + + $tokens[$operandIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "''"]); + $tokens[$operatorIndex] = new Token([$replacement, $operandContent]); + + if (!$keepParentheses) { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + } + + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + + if (null !== $namespaceSeparatorIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex); + } + } + } + + private function getReplacementYoda(Token $operator, Token $operand): ?int + { + /* Yoda 0 + + 0 === strlen($b) | '' === $b + 0 !== strlen($b) | '' !== $b + 0 <= strlen($b) | X makes no sense, assume overridden + 0 >= strlen($b) | '' === $b + 0 < strlen($b) | '' !== $b + 0 > strlen($b) | X makes no sense, assume overridden + */ + + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_GREATER_OR_EQUAL])) { + return \T_IS_IDENTICAL; + } + + if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('<')) { + return \T_IS_NOT_IDENTICAL; + } + + return null; + } + + /* Yoda 1 + + 1 === strlen($b) | X cannot simplify + 1 !== strlen($b) | X cannot simplify + 1 <= strlen($b) | '' !== $b + 1 >= strlen($b) | cannot simplify + 1 < strlen($b) | cannot simplify + 1 > strlen($b) | '' === $b + */ + + if ($operator->isGivenKind(\T_IS_SMALLER_OR_EQUAL)) { + return \T_IS_NOT_IDENTICAL; + } + + if ($operator->equals('>')) { + return \T_IS_IDENTICAL; + } + + return null; + } + + private function getReplacementNotYoda(Token $operator, Token $operand): ?int + { + /* Not Yoda 0 + + strlen($b) === 0 | $b === '' + strlen($b) !== 0 | $b !== '' + strlen($b) <= 0 | $b === '' + strlen($b) >= 0 | X makes no sense, assume overridden + strlen($b) < 0 | X makes no sense, assume overridden + strlen($b) > 0 | $b !== '' + */ + + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_SMALLER_OR_EQUAL])) { + return \T_IS_IDENTICAL; + } + + if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('>')) { + return \T_IS_NOT_IDENTICAL; + } + + return null; + } + + /* Not Yoda 1 + + strlen($b) === 1 | X cannot simplify + strlen($b) !== 1 | X cannot simplify + strlen($b) <= 1 | X cannot simplify + strlen($b) >= 1 | $b !== '' + strlen($b) < 1 | $b === '' + strlen($b) > 1 | X cannot simplify + */ + + if ($operator->isGivenKind(\T_IS_GREATER_OR_EQUAL)) { + return \T_IS_NOT_IDENTICAL; + } + + if ($operator->equals('<')) { + return \T_IS_IDENTICAL; + } + + return null; + } + + private function isOperandOfInterest(Token $token): bool + { + if (!$token->isGivenKind(\T_LNUMBER)) { + return false; + } + + $content = $token->getContent(); + + return '0' === $content || '1' === $content; + } + + private function isOperatorOfInterest(Token $token): bool + { + return + $token->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, \T_IS_GREATER_OR_EQUAL]) + || $token->equals('<') || $token->equals('>'); + } + + private function isOfHigherPrecedence(Token $token): bool + { + return $token->isGivenKind([\T_INSTANCEOF, \T_POW, \T_SL, \T_SR]) || $token->equalsAny([ + '!', + '%', + '*', + '+', + '-', + '.', + '/', + '~', + '?', + ]); + } + + private function keepParentheses(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool + { + $i = $tokens->getNextMeaningfulToken($openParenthesisIndex); + + if ($tokens[$i]->isCast()) { + $i = $tokens->getNextMeaningfulToken($i); + } + + for (; $i < $closeParenthesisIndex; ++$i) { + $token = $tokens[$i]; + + if ($token->isGivenKind([\T_VARIABLE, \T_STRING]) || $token->isObjectOperator() || $token->isWhitespace() || $token->isComment()) { + continue; + } + + $blockType = Tokens::detectBlockType($token); + + if (null !== $blockType && $blockType['isStart']) { + $i = $tokens->findBlockEnd($blockType['type'], $i); + + continue; + } + + return true; + } + + return false; + } + + /** + * @return iterable + */ + private function findStrLengthCalls(Tokens $tokens): iterable + { + $candidates = []; + $count = \count($tokens); + + for ($i = 0; $i < $count; ++$i) { + $candidate = $this->find('strlen', $tokens, $i, $count); + + if (null === $candidate) { + break; + } + + $i = $candidate[1]; // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + + foreach (array_reverse($candidates) as $candidate) { + yield $candidate; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php new file mode 100644 index 0000000..ba3601b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixes the line endings in multi-line strings. + * + * @author Ilija Tovilo + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StringLineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]); + } + + public function isRisky(): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All multi-line strings must use correct line ending.', + [ + new CodeSample( + "whitespacesConfig->getLineEnding(); + + foreach ($tokens as $tokenIndex => $token) { + if (!$token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML])) { + continue; + } + + $tokens[$tokenIndex] = new Token([ + $token->getId(), + Preg::replace( + '#\R#u', + $ending, + $token->getContent(), + ), + ]); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php new file mode 100644 index 0000000..e579a16 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use IndentationTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each element of an array must be indented exactly once.', + [ + new CodeSample(" [\n 'baz' => true,\n ],\n];\n"), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, \T_LIST, CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN]); + } + + /** + * {@inheritdoc} + * + * Must run before AlignMultilineCommentFixer, BinaryOperatorSpacesFixer. + * Must run after MethodArgumentSpaceFixer. + */ + public function getPriority(): int + { + return 29; + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lastIndent = ''; + + /** @var list $scopes */ + $scopes = []; + $previousLineInitialIndent = ''; + $previousLineNewIndent = ''; + + foreach ($tokens as $index => $token) { + $currentScope = [] !== $scopes ? \count($scopes) - 1 : null; + + if ($token->isComment()) { + continue; + } + + if ( + $token->isGivenKind([CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN]) + || ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([\T_ARRAY, \T_LIST])) + ) { + $blockType = Tokens::detectBlockType($token); + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + + $scopes[] = [ + 'type' => 'array', + 'end_index' => $endIndex, + 'initial_indent' => $lastIndent, + ]; + + continue; + } + + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + + if (null === $currentScope) { + continue; + } + + \assert(isset($scopes[$currentScope])); + + if ($token->isWhitespace()) { + if (!Preg::match('/\R/', $token->getContent())) { + continue; + } + + if ('array' === $scopes[$currentScope]['type']) { + $indent = false; + + for ($searchEndIndex = $index + 1; $searchEndIndex < $scopes[$currentScope]['end_index']; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ( + (!$searchEndToken->isWhitespace() && !$searchEndToken->isComment()) + || ($searchEndToken->isWhitespace() && Preg::match('/\R/', $searchEndToken->getContent())) + ) { + $indent = true; + + break; + } + } + + $content = Preg::replace( + '/(\R+)\h*$/', + '$1'.$scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''), + $token->getContent(), + ); + + $previousLineInitialIndent = $this->extractIndent($token->getContent()); + $previousLineNewIndent = $this->extractIndent($content); + } else { + $content = Preg::replace( + '/(\R)'.preg_quote($scopes[$currentScope]['initial_indent'], '/').'(\h*)$/', + '$1'.$scopes[$currentScope]['new_indent'].'$2', + $token->getContent(), + ); + } + + $tokens[$index] = new Token([\T_WHITESPACE, $content]); + $lastIndent = $this->extractIndent($content); + + continue; + } + + if ($index === $scopes[$currentScope]['end_index']) { + while ([] !== $scopes && $index === $scopes[$currentScope]['end_index']) { + array_pop($scopes); + --$currentScope; + } + + continue; + } + + if ($token->equals(',')) { + continue; + } + + if ('expression' !== $scopes[$currentScope]['type']) { + $endIndex = $this->findExpressionEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); + + if ($endIndex === $index) { + continue; + } + + $scopes[] = [ + 'type' => 'expression', + 'end_index' => $endIndex, + 'initial_indent' => $previousLineInitialIndent, + 'new_indent' => $previousLineNewIndent, + ]; + } + } + } + + private function findExpressionEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int + { + $endIndex = null; + + for ($searchEndIndex = $index + 1; $searchEndIndex < $parentScopeEndIndex; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ($searchEndToken->equalsAny(['(', '{']) + || $searchEndToken->isGivenKind([CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN]) + ) { + $type = Tokens::detectBlockType($searchEndToken); + $searchEndIndex = $tokens->findBlockEnd( + $type['type'], + $searchEndIndex, + ); + + continue; + } + + if ($searchEndToken->equals(',')) { + $endIndex = $tokens->getPrevMeaningfulToken($searchEndIndex); + + break; + } + } + + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php new file mode 100644 index 0000000..7b10fe3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php @@ -0,0 +1,405 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * statements?: list<'break'|'case'|'continue'|'declare'|'default'|'do'|'exit'|'for'|'foreach'|'goto'|'if'|'include'|'include_once'|'phpdoc'|'require'|'require_once'|'return'|'switch'|'throw'|'try'|'while'|'yield'|'yield_from'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * statements: list<'break'|'case'|'continue'|'declare'|'default'|'do'|'exit'|'for'|'foreach'|'goto'|'if'|'include'|'include_once'|'phpdoc'|'require'|'require_once'|'return'|'switch'|'throw'|'try'|'while'|'yield'|'yield_from'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var array + */ + private const TOKEN_MAP = [ + 'break' => \T_BREAK, + 'case' => \T_CASE, + 'continue' => \T_CONTINUE, + 'declare' => \T_DECLARE, + 'default' => \T_DEFAULT, + 'do' => \T_DO, + 'exit' => \T_EXIT, + 'for' => \T_FOR, + 'foreach' => \T_FOREACH, + 'goto' => \T_GOTO, + 'if' => \T_IF, + 'include' => \T_INCLUDE, + 'include_once' => \T_INCLUDE_ONCE, + 'phpdoc' => \T_DOC_COMMENT, + 'require' => \T_REQUIRE, + 'require_once' => \T_REQUIRE_ONCE, + 'return' => \T_RETURN, + 'switch' => \T_SWITCH, + 'throw' => \T_THROW, + 'try' => \T_TRY, + 'while' => \T_WHILE, + 'yield' => \T_YIELD, + 'yield_from' => \T_YIELD_FROM, + ]; + + /** + * @var list + */ + private array $fixTokenMap = []; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'An empty line feed must precede any configured statement.', + [ + new CodeSample( + <<<'PHP' + process(); + break; + case 44: + break; + } + + PHP, + [ + 'statements' => ['break'], + ], + ), + new CodeSample( + <<<'PHP' + isTired()) { + $bar->sleep(); + continue; + } + } + + PHP, + [ + 'statements' => ['continue'], + ], + ), + new CodeSample( + <<<'PHP' + 0); + + PHP, + [ + 'statements' => ['do'], + ], + ), + new CodeSample( + <<<'PHP' + ['exit'], + ], + ), + new CodeSample( + <<<'PHP' + ['goto'], + ], + ), + new CodeSample( + <<<'PHP' + ['if'], + ], + ), + new CodeSample( + <<<'PHP' + ['return'], + ], + ), + new CodeSample( + <<<'PHP' + ['switch'], + ], + ), + new CodeSample( + <<<'PHP' + bar(); + throw new \UnexpectedValueException("A cannot be null."); + } + + PHP, + [ + 'statements' => ['throw'], + ], + ), + new CodeSample( + <<<'PHP' + bar(); + } catch (\Exception $exception) { + $a = -1; + } + + PHP, + [ + 'statements' => ['try'], + ], + ), + new CodeSample( + <<<'PHP' + ['yield'], + ], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoExtraBlankLinesFixer, NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority(): int + { + return -21; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound($this->fixTokenMap); + } + + protected function configurePostNormalisation(): void + { + $fixTokenMap = []; + + foreach ($this->configuration['statements'] as $key) { + $fixTokenMap[$key] = self::TOKEN_MAP[$key]; + } + + $this->fixTokenMap = array_values($fixTokenMap); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $analyzer = new TokensAnalyzer($tokens); + + for ($index = $tokens->count() - 1; $index > 0; --$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind($this->fixTokenMap)) { + continue; + } + + if ($token->isGivenKind(\T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { + continue; + } + + if ($token->isGivenKind(\T_CASE) && $analyzer->isEnumCase($index)) { + continue; + } + + $insertBlankLineIndex = $this->getInsertBlankLineIndex($tokens, $index); + $prevNonWhitespace = $tokens->getPrevNonWhitespace($insertBlankLineIndex); + + if ($this->shouldAddBlankLine($tokens, $prevNonWhitespace)) { + $this->insertBlankLine($tokens, $insertBlankLineIndex); + } + + $index = $prevNonWhitespace; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(array_keys(self::TOKEN_MAP))]) + ->setDefault([ + 'break', + 'continue', + 'declare', + 'return', + 'throw', + 'try', + ]) + ->getOption(), + ]); + } + + private function getInsertBlankLineIndex(Tokens $tokens, int $index): int + { + while ($index > 0) { + if ($tokens[$index - 1]->isWhitespace() && substr_count($tokens[$index - 1]->getContent(), "\n") > 1) { + break; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if (!$tokens[$prevIndex]->isComment()) { + break; + } + + if (!$tokens[$prevIndex - 1]->isWhitespace()) { + break; + } + + if (1 !== substr_count($tokens[$prevIndex - 1]->getContent(), "\n")) { + break; + } + + $index = $prevIndex; + } + + return $index; + } + + private function shouldAddBlankLine(Tokens $tokens, int $prevNonWhitespace): bool + { + $prevNonWhitespaceToken = $tokens[$prevNonWhitespace]; + + if ($prevNonWhitespaceToken->isComment()) { + for ($j = $prevNonWhitespace - 1; $j >= 0; --$j) { + if (str_contains($tokens[$j]->getContent(), "\n")) { + return false; + } + + if ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) { + continue; + } + + return $tokens[$j]->equalsAny([';', '}']); + } + } + + return $prevNonWhitespaceToken->equalsAny([';', '}']); + } + + private function insertBlankLine(Tokens $tokens, int $index): void + { + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + if ($prevToken->isWhitespace()) { + $newlinesCount = substr_count($prevToken->getContent(), "\n"); + + if (0 === $newlinesCount) { + $tokens[$prevIndex] = new Token([\T_WHITESPACE, rtrim($prevToken->getContent(), " \t").$lineEnding.$lineEnding]); + } elseif (1 === $newlinesCount) { + $tokens[$prevIndex] = new Token([\T_WHITESPACE, $lineEnding.$prevToken->getContent()]); + } + } else { + $tokens->insertAt($index, new Token([\T_WHITESPACE, $lineEnding.$lineEnding])); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php new file mode 100644 index 0000000..12f043f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php @@ -0,0 +1,191 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author Sander Verkuil + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlankLineBetweenImportGroupsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + private const IMPORT_TYPE_CLASS = 'class'; + + private const IMPORT_TYPE_CONST = 'const'; + + private const IMPORT_TYPE_FUNCTION = 'function'; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Putting blank lines between `use` statement groups.', + [ + new CodeSample( + <<<'PHP' + isTokenKindFound(\T_USE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); + + foreach (array_reverse($namespacesImports) as $uses) { + $this->walkOverUses($tokens, $uses); + } + } + + /** + * @param list $uses + */ + private function walkOverUses(Tokens $tokens, array $uses): void + { + $usesCount = \count($uses); + + if ($usesCount < 2) { + return; // nothing to fix + } + + $previousType = null; + + for ($i = $usesCount - 1; $i >= 0; --$i) { + \assert(isset($uses[$i])); + $index = $uses[$i]; + $startIndex = $tokens->getNextMeaningfulToken($index + 1); + $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [\T_CLOSE_TAG]]); + + if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $type = self::IMPORT_TYPE_CONST; + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = self::IMPORT_TYPE_FUNCTION; + } else { + $type = self::IMPORT_TYPE_CLASS; + } + + if (null !== $previousType && $type !== $previousType) { + $this->ensureLine($tokens, $endIndex + 1); + } + + $previousType = $type; + } + } + + private function ensureLine(Tokens $tokens, int $index): void + { + static $lineEnding; + + if (null === $lineEnding) { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $lineEnding .= $lineEnding; + } + + $index = $this->getInsertIndex($tokens, $index); + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + + $tokens->ensureWhitespaceAtIndex($index, 1, $lineEnding.$indent); + } + + private function getInsertIndex(Tokens $tokens, int $index): int + { + $tokensCount = \count($tokens); + + for (; $index < $tokensCount - 1; ++$index) { + if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) { + return $index - 1; + } + + $content = $tokens[$index]->getContent(); + + if (str_contains($content, "\n")) { + break; + } + } + + return $index; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php new file mode 100644 index 0000000..9e31fa0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Jack Cherng + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CompactNullableTypeDeclarationFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove extra spaces in a nullable type declaration.', + [ + new CodeSample( + "isTokenKindFound(CT::T_NULLABLE_TYPE); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + continue; + } + + // remove whitespaces only if there are only whitespaces + // between '?' and the variable type + if ( + $tokens[$index + 1]->isWhitespace() + && $tokens[$index + 2]->isGivenKind([ + CT::T_ARRAY_TYPEHINT, + \T_CALLABLE, + \T_NS_SEPARATOR, + \T_STATIC, + \T_STRING, + ]) + ) { + $tokens->removeTrailingWhitespace($index); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php new file mode 100644 index 0000000..385fbfb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; + +/** + * @author Jack Cherng + * + * @deprecated + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CompactNullableTypehintFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + private CompactNullableTypeDeclarationFixer $compactNullableTypeDeclarationFixer; + + public function __construct() + { + $this->compactNullableTypeDeclarationFixer = new CompactNullableTypeDeclarationFixer(); + + parent::__construct(); + } + + public function getDefinition(): FixerDefinitionInterface + { + $fixerDefinition = $this->compactNullableTypeDeclarationFixer->getDefinition(); + + return new FixerDefinition( + 'Remove extra spaces in a nullable typehint.', + $fixerDefinition->getCodeSamples(), + $fixerDefinition->getDescription(), + $fixerDefinition->getRiskyDescription(), + ); + } + + public function getSuccessorsNames(): array + { + return [ + $this->compactNullableTypeDeclarationFixer->getName(), + ]; + } + + protected function createProxyFixers(): array + { + return [ + $this->compactNullableTypeDeclarationFixer, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php new file mode 100644 index 0000000..b5ea1d2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php @@ -0,0 +1,182 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * indentation?: 'same_as_start'|'start_plus_one', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * indentation: 'same_as_start'|'start_plus_one', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class HeredocIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Heredoc/nowdoc content must be properly indented.', + [ + new CodeSample( + <<<'SAMPLE' + 'same_as_start'], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run after BracesFixer, MultilineStringToHeredocFixer, StatementIndentationFixer. + */ + public function getPriority(): int + { + return -26; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound(\T_START_HEREDOC); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('indentation', 'Whether the indentation should be the same as in the start token line or one level more.')) + ->setAllowedValues(['start_plus_one', 'same_as_start']) + ->setDefault('start_plus_one') + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_END_HEREDOC)) { + continue; + } + + $end = $index; + $index = $tokens->getPrevTokenOfKind($index, [[\T_START_HEREDOC]]); + + $this->fixIndentation($tokens, $index, $end); + } + } + + private function fixIndentation(Tokens $tokens, int $start, int $end): void + { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $start); + + if ('start_plus_one' === $this->configuration['indentation']) { + $indent .= $this->whitespacesConfig->getIndent(); + } + + Preg::match('/^\h*/', $tokens[$end]->getContent(), $matches); + \assert(isset($matches[0])); + $currentIndent = $matches[0]; + $currentIndentLength = \strlen($currentIndent); + + $content = $indent.substr($tokens[$end]->getContent(), $currentIndentLength); + $tokens[$end] = new Token([\T_END_HEREDOC, $content]); + + if ($end === $start + 1) { + return; + } + + $index = $end - 1; + + for ($last = true; $index > $start; --$index, $last = false) { + if (!$tokens[$index]->isGivenKind([\T_ENCAPSED_AND_WHITESPACE, \T_WHITESPACE])) { + continue; + } + + $content = $tokens[$index]->getContent(); + + if ('' !== $currentIndent) { + $content = Preg::replace('/(?<=\v)(?!'.$currentIndent.')\h+/', '', $content); + } + + $regexEnd = $last && '' === $currentIndent ? '(?!\v|$)' : '(?!\v)'; + $content = Preg::replace('/(?<=\v)'.$currentIndent.$regexEnd.'/', $indent, $content); + + $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); + } + + ++$index; + + if (!$tokens[$index]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + $tokens->insertAt($index, new Token([\T_ENCAPSED_AND_WHITESPACE, $indent])); + + return; + } + + $content = $tokens[$index]->getContent(); + + if (!\in_array($content[0], ["\r", "\n"], true) && ('' === $currentIndent || str_starts_with($content, $currentIndent))) { + $content = $indent.substr($content, $currentIndentLength); + } elseif ('' !== $currentIndent) { + $content = Preg::replace('/^(?!'.$currentIndent.')\h+/', '', $content); + } + + $tokens[$index] = new Token([\T_ENCAPSED_AND_WHITESPACE, $content]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php new file mode 100644 index 0000000..b8c33dd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php @@ -0,0 +1,142 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.4. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class IndentationTypeFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + private string $indent; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Code MUST use configured indentation type.', + [ + new CodeSample("isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->indent = $this->whitespacesConfig->getIndent(); + + foreach ($tokens as $index => $token) { + if ($token->isComment()) { + $tokens[$index] = $this->fixIndentInComment($tokens, $index); + + continue; + } + + if ($token->isWhitespace()) { + $tokens[$index] = $this->fixIndentToken($tokens, $index); + + continue; + } + } + } + + private function fixIndentInComment(Tokens $tokens, int $index): Token + { + $content = Preg::replace('/^(?:(?getContent(), -1, $count); + + // Also check for more tabs. + while (0 !== $count) { + $content = Preg::replace('/^(\ +)?\t/m', '\1 ', $content, -1, $count); + } + + $indent = $this->indent; + + // change indent to expected one + $content = Preg::replaceCallback('/^(?: )+/m', fn (array $matches): string => $this->getExpectedIndent($matches[0], $indent), $content); + + return new Token([$tokens[$index]->getId(), $content]); + } + + private function fixIndentToken(Tokens $tokens, int $index): Token + { + $content = $tokens[$index]->getContent(); + $previousTokenHasTrailingLinebreak = false; + + // @TODO this can be removed when we have a transformer for "T_OPEN_TAG" to "T_OPEN_TAG + T_WHITESPACE" + if (str_contains($tokens[$index - 1]->getContent(), "\n")) { + $content = "\n".$content; + $previousTokenHasTrailingLinebreak = true; + } + + $indent = $this->indent; + $newContent = Preg::replaceCallback( + '/(\R)(\h+)/', // find indent + function (array $matches) use ($indent): string { + \assert(isset($matches[1], $matches[2])); + // normalize mixed indent + $content = Preg::replace('/(?:(?getExpectedIndent($content, $indent); + }, + $content, + ); + + if ($previousTokenHasTrailingLinebreak) { + $newContent = substr($newContent, 1); + } + + return new Token([\T_WHITESPACE, $newContent]); + } + + /** + * @return string mixed + */ + private function getExpectedIndent(string $content, string $indent): string + { + if ("\t" === $indent) { + $content = str_replace(' ', $indent, $content); + } + + return $content; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php new file mode 100644 index 0000000..3f9d3a8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'All PHP files must use same line ending.', + [ + new CodeSample( + "whitespacesConfig->getLineEnding(); + + for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_END_HEREDOC)) { + $tokens[$index] = new Token([ + $token->getId(), + Preg::replace( + '#\R#', + $ending, + $token->getContent(), + ), + ]); + } + + continue; + } + + if ($token->isGivenKind([\T_CLOSE_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG, \T_START_HEREDOC, \T_WHITESPACE])) { + $tokens[$index] = new Token([ + $token->getId(), + Preg::replace( + '#\R#', + $ending, + $token->getContent(), + ), + ]); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php new file mode 100644 index 0000000..d5d5058 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php @@ -0,0 +1,231 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Vladimir Boliev + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MethodChainingIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Method chaining MUST be properly indented. Method chaining with different levels of indentation is not supported.', + [new CodeSample("setEmail('voff.web@gmail.com')\n ->setPassword('233434');\n")], + ); + } + + /** + * {@inheritdoc} + * + * Must run after NoSpaceAroundDoubleColonFixer. + */ + public function getPriority(): int + { + return 0; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + + $endParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', ',', [\T_CLOSE_TAG]]); + $previousEndParenthesisIndex = $tokens->getPrevTokenOfKind($index, [')']); + + if ( + null === $endParenthesisIndex + || !$tokens[$endParenthesisIndex]->equals('(') && null === $previousEndParenthesisIndex + ) { + continue; + } + + if ($this->canBeMovedToNextLine($index, $tokens)) { + $newline = new Token([\T_WHITESPACE, $lineEnding]); + + if ($tokens[$index - 1]->isWhitespace()) { + $tokens[$index - 1] = $newline; + } else { + $tokens->insertAt($index, $newline); + ++$index; + ++$endParenthesisIndex; + } + } + + $currentIndent = $this->getIndentAt($tokens, $index - 1); + + if (null === $currentIndent) { + continue; + } + + $expectedIndent = $this->getExpectedIndentAt($tokens, $index); + + if ($currentIndent !== $expectedIndent) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, $lineEnding.$expectedIndent]); + } + + if (!$tokens[$endParenthesisIndex]->equals('(')) { + continue; + } + + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $endParenthesisIndex); + + for ($searchIndex = $index + 1; $searchIndex < $endParenthesisIndex; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + + if (!$searchToken->isWhitespace()) { + continue; + } + + $content = $searchToken->getContent(); + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $content = Preg::replace( + '/(\R)'.$currentIndent.'(\h*)$/D', + '$1'.$expectedIndent.'$2', + $content, + ); + + $tokens[$searchIndex] = new Token([$searchToken->getId(), $content]); + } + } + } + + /** + * @param int $index index of the first token on the line to indent + */ + private function getExpectedIndentAt(Tokens $tokens, int $index): string + { + $index = $tokens->getPrevMeaningfulToken($index); + $indent = $this->whitespacesConfig->getIndent(); + + for ($i = $index; $i >= 0; --$i) { + if ($tokens[$i]->equals(')')) { + $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $i); + } + + $currentIndent = $this->getIndentAt($tokens, $i); + if (null === $currentIndent) { + continue; + } + + if ($this->currentLineRequiresExtraIndentLevel($tokens, $i, $index)) { + return $currentIndent.$indent; + } + + return $currentIndent; + } + + return $indent; + } + + /** + * @param int $index position of the object operator token ("->" or "?->") + */ + private function canBeMovedToNextLine(int $index, Tokens $tokens): bool + { + $prevMeaningful = $tokens->getPrevMeaningfulToken($index); + $hasCommentBefore = false; + + for ($i = $index - 1; $i > $prevMeaningful; --$i) { + if ($tokens[$i]->isComment()) { + $hasCommentBefore = true; + + continue; + } + + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) { + return $hasCommentBefore; + } + } + + return false; + } + + /** + * @param int $index index of the indentation token + */ + private function getIndentAt(Tokens $tokens, int $index): ?string + { + if (Preg::match('/\R{1}(\h*)$/', $this->getIndentContentAt($tokens, $index), $matches)) { + return $matches[1]; + } + + return null; + } + + private function getIndentContentAt(Tokens $tokens, int $index): string + { + if (!$tokens[$index]->isGivenKind([\T_WHITESPACE, \T_INLINE_HTML])) { + return ''; + } + + $content = $tokens[$index]->getContent(); + + if ($tokens[$index]->isWhitespace() && $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) { + $content = $tokens[$index - 1]->getContent().$content; + } + + if (Preg::match('/\R/', $content)) { + return $content; + } + + return ''; + } + + /** + * @param int $start index of first meaningful token on previous line + * @param int $end index of last token on previous line + */ + private function currentLineRequiresExtraIndentLevel(Tokens $tokens, int $start, int $end): bool + { + $firstMeaningful = $tokens->getNextMeaningfulToken($start); + + if ($tokens[$firstMeaningful]->isObjectOperator()) { + $thirdMeaningful = $tokens->getNextMeaningfulToken($tokens->getNextMeaningfulToken($firstMeaningful)); + + return + $tokens[$thirdMeaningful]->equals('(') + && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $thirdMeaningful) > $end; + } + + return + !$tokens[$end]->equals(')') + || $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $end) >= $start; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php new file mode 100644 index 0000000..f48aa5a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php @@ -0,0 +1,531 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * tokens?: list<'attribute'|'break'|'case'|'comma'|'continue'|'curly_brace_block'|'default'|'extra'|'parenthesis_brace_block'|'return'|'square_brace_block'|'switch'|'throw'|'use'|'use_trait'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * tokens: list<'attribute'|'break'|'case'|'comma'|'continue'|'curly_brace_block'|'default'|'extra'|'parenthesis_brace_block'|'return'|'square_brace_block'|'switch'|'throw'|'use'|'use_trait'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoExtraBlankLinesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + /** + * @var non-empty-list + */ + private const AVAILABLE_TOKENS = [ + 'attribute', + 'break', + 'case', + 'comma', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'switch', + 'throw', + 'use', + 'use_trait', + ]; + + /** + * @var array key is token id + */ + private array $tokenKindCallbackMap; + + /** + * @var array key is token's content + */ + private array $tokenEqualsMap; + + private Tokens $tokens; + + private TokensAnalyzer $tokensAnalyzer; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Removes extra blank lines and/or blank lines following configuration.', + [ + new CodeSample( + <<<'PHP' + ['break']], + ), + new CodeSample( + <<<'PHP' + ['continue']], + ), + new CodeSample( + <<<'PHP' + ['curly_brace_block']], + ), + new CodeSample( + <<<'PHP' + ['extra']], + ), + new CodeSample( + <<<'PHP' + ['parenthesis_brace_block']], + ), + new CodeSample( + <<<'PHP' + ['return']], + ), + new CodeSample( + <<<'PHP' + ['square_brace_block']], + ), + new CodeSample( + <<<'PHP' + ['throw']], + ), + new CodeSample( + <<<'PHP' + ['use']], + ), + new CodeSample( + <<<'PHP' + ['switch', 'case', 'default']], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer. + * Must run after ClassAttributesSeparationFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, EmptyLoopConditionFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoEmptyStatementFixer, NoUnusedImportsFixer, NoUselessElseFixer, NoUselessPrintfFixer, NoUselessReturnFixer, NoUselessSprintfFixer, PhpdocReadonlyClassCommentToKeywordFixer, StringLengthToEmptyFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority(): int + { + return -20; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + /** + * @param _AutogeneratedInputConfiguration $configuration + */ + protected function configurePreNormalisation(array $configuration): void + { + if (isset($configuration['tokens']) && \in_array('use_trait', $configuration['tokens'], true)) { + Future::triggerDeprecation(new \RuntimeException('Option "tokens: use_trait" used in `no_extra_blank_lines` rule is deprecated, use the rule `class_attributes_separation` with `elements: trait_import` instead.')); + } + } + + protected function configurePostNormalisation(): void + { + $tokensConfiguration = $this->configuration['tokens']; + + $this->tokenEqualsMap = []; + + if (\in_array('comma', $tokensConfiguration, true)) { + $this->tokenEqualsMap[','] = [$this, 'fixAfterToken']; + } + + if (\in_array('curly_brace_block', $tokensConfiguration, true)) { + $this->tokenEqualsMap['{'] = [$this, 'fixStructureOpenCloseIfMultiLine']; // i.e. not: CT::T_ARRAY_INDEX_BRACE_OPEN + } + + if (\in_array('parenthesis_brace_block', $tokensConfiguration, true)) { + $this->tokenEqualsMap['('] = [$this, 'fixStructureOpenCloseIfMultiLine']; // i.e. not: CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN + } + + // Each item requires explicit array-like callable, otherwise PHPStan will complain about unused private methods. + $configMap = [ + 'attribute' => [CT::T_ATTRIBUTE_CLOSE, [$this, 'fixAfterToken']], + 'break' => [\T_BREAK, [$this, 'fixAfterToken']], + 'case' => [\T_CASE, [$this, 'fixAfterCaseToken']], + 'continue' => [\T_CONTINUE, [$this, 'fixAfterToken']], + 'default' => [\T_DEFAULT, [$this, 'fixAfterToken']], + 'extra' => [\T_WHITESPACE, [$this, 'removeMultipleBlankLines']], + 'return' => [\T_RETURN, [$this, 'fixAfterToken']], + 'square_brace_block' => [CT::T_ARRAY_BRACKET_OPEN, [$this, 'fixStructureOpenCloseIfMultiLine']], + 'switch' => [\T_SWITCH, [$this, 'fixAfterToken']], + 'throw' => [\T_THROW, [$this, 'fixAfterThrowToken']], + 'use' => [\T_USE, [$this, 'removeBetweenUse']], + 'use_trait' => [CT::T_USE_TRAIT, [$this, 'removeBetweenUse']], + ]; + + $this->tokenKindCallbackMap = []; + + foreach ($tokensConfiguration as $config) { + if (isset($configMap[$config])) { + $this->tokenKindCallbackMap[$configMap[$config][0]] = $configMap[$config][1]; + } + } + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->tokens = $tokens; + $this->tokensAnalyzer = new TokensAnalyzer($this->tokens); + + for ($index = $tokens->getSize() - 1; $index > 0; --$index) { + $this->fixByToken($tokens[$index], $index); + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('tokens', 'List of tokens to fix.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(self::AVAILABLE_TOKENS)]) + ->setDefault(['extra']) + ->getOption(), + ]); + } + + /** + * @uses fixAfterToken() + * @uses fixAfterCaseToken() + * @uses fixAfterThrowToken() + * @uses fixStructureOpenCloseIfMultiLine() + * @uses removeBetweenUse() + * @uses removeMultipleBlankLines() + */ + private function fixByToken(Token $token, int $index): void + { + foreach ($this->tokenKindCallbackMap as $kind => $callback) { + if (!$token->isGivenKind($kind)) { + continue; + } + + \assert(isset($this->tokenKindCallbackMap[$token->getId()])); + \call_user_func_array($this->tokenKindCallbackMap[$token->getId()], [$index]); + + return; + } + + foreach ($this->tokenEqualsMap as $equals => $callback) { + if (!$token->equals($equals)) { + continue; + } + + \assert(isset($this->tokenEqualsMap[$token->getContent()])); + \call_user_func_array($this->tokenEqualsMap[$token->getContent()], [$index]); + + return; + } + } + + private function removeBetweenUse(int $index): void + { + $next = $this->tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + + if (null === $next || $this->tokens[$next]->isGivenKind(\T_CLOSE_TAG)) { + return; + } + + $nextUseCandidate = $this->tokens->getNextMeaningfulToken($next); + + if (null === $nextUseCandidate || !$this->tokens[$nextUseCandidate]->isGivenKind($this->tokens[$index]->getId()) || !$this->containsLinebreak($index, $nextUseCandidate)) { + return; + } + + $this->removeEmptyLinesAfterLineWithTokenAt($next); + } + + private function removeMultipleBlankLines(int $index): void + { + $expected = $this->tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R$/', $this->tokens[$index - 1]->getContent()) ? 1 : 2; + + $parts = Preg::split('/(.*\R)/', $this->tokens[$index]->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + $count = \count($parts); + + if ($count > $expected) { + \assert(isset($parts[$count - 1])); + $this->tokens[$index] = new Token([\T_WHITESPACE, implode('', \array_slice($parts, 0, $expected)).rtrim($parts[$count - 1], "\r\n")]); + } + } + + private function fixAfterToken(int $index): void + { + for ($i = $index - 1; $i > 0; --$i) { + if ($this->tokens[$i]->isGivenKind(\T_FUNCTION) && $this->tokensAnalyzer->isLambda($i)) { + return; + } + + if ($this->tokens[$i]->isGivenKind(\T_CLASS) && $this->tokensAnalyzer->isAnonymousClass($i)) { + return; + } + + if ($this->tokens[$i]->isGivenKind([CT::T_ARRAY_BRACKET_OPEN, CT::T_DESTRUCTURING_BRACKET_OPEN])) { + return; + } + + if ($this->tokens[$i]->isWhitespace() && str_contains($this->tokens[$i]->getContent(), "\n")) { + break; + } + } + + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + + private function fixAfterCaseToken(int $index): void + { + $enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[\T_SWITCH], [FCT::T_ENUM]]); + + if (!$this->tokens[$enumSwitchIndex]->isGivenKind(\T_SWITCH)) { + return; + } + + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + + private function fixAfterThrowToken(int $index): void + { + $prevIndex = $this->tokens->getPrevMeaningfulToken($index); + + if (!$this->tokens[$prevIndex]->equalsAny([';', '{', '}', ':', [\T_OPEN_TAG]])) { + return; + } + + if ($this->tokens[$prevIndex]->equals(':') && !SwitchAnalyzer::belongsToSwitch($this->tokens, $prevIndex)) { + return; + } + + $this->fixAfterToken($index); + } + + /** + * Remove white line(s) after the index of a block type, + * but only if the block is not on one line. + * + * @param int $index body start + */ + private function fixStructureOpenCloseIfMultiLine(int $index): void + { + $blockTypeInfo = Tokens::detectBlockType($this->tokens[$index]); + $bodyEnd = $this->tokens->findBlockEnd($blockTypeInfo['type'], $index); + + for ($i = $bodyEnd - 1; $i >= $index; --$i) { + if (str_contains($this->tokens[$i]->getContent(), "\n")) { + $this->removeEmptyLinesAfterLineWithTokenAt($i); + $this->removeEmptyLinesAfterLineWithTokenAt($index); + + break; + } + } + } + + private function removeEmptyLinesAfterLineWithTokenAt(int $index): void + { + // find the line break + $parenthesesDepth = 0; + $tokenCount = \count($this->tokens); + for ($end = $index; $end < $tokenCount; ++$end) { + if ($this->tokens[$end]->equals('(')) { + ++$parenthesesDepth; + + continue; + } + + if ($this->tokens[$end]->equals(')')) { + --$parenthesesDepth; + if ($parenthesesDepth < 0) { + return; + } + + continue; + } + + if ( + $this->tokens[$end]->equals('}') + || str_contains($this->tokens[$end]->getContent(), "\n") + ) { + break; + } + } + + if ($end === $tokenCount) { + return; // not found, early return + } + + $ending = $this->whitespacesConfig->getLineEnding(); + + for ($i = $end; $i < $tokenCount && $this->tokens[$i]->isWhitespace(); ++$i) { + $content = $this->tokens[$i]->getContent(); + + if (substr_count($content, "\n") < 1) { + continue; + } + + $newContent = Preg::replace('/^.*\R(\h*)$/s', $ending.'$1', $content); + + $this->tokens[$i] = new Token([\T_WHITESPACE, $newContent]); + } + } + + private function containsLinebreak(int $startIndex, int $endIndex): bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\R/', $this->tokens[$i]->getContent())) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php new file mode 100644 index 0000000..6b738a2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php @@ -0,0 +1,114 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * positions?: list<'inside'|'outside'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * positions: list<'inside'|'outside'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Javier Spagnoletti + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSpacesAroundOffsetFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be spaces around offset braces.', + [ + new CodeSample(" ['inside']]), + new CodeSample(" ['outside']]), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['[', CT::T_ARRAY_INDEX_BRACE_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['[', [CT::T_ARRAY_INDEX_BRACE_OPEN]])) { + continue; + } + + if (\in_array('inside', $this->configuration['positions'], true)) { + if ($token->equals('[')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACKET, $index); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACE, $index); + } + + // remove space after opening `[` or `{` + if ($tokens[$index + 1]->isWhitespace(" \t")) { + $tokens->clearAt($index + 1); + } + + // remove space before closing `]` or `}` + if ($tokens[$endIndex - 1]->isWhitespace(" \t")) { + $tokens->clearAt($endIndex - 1); + } + } + + if (\in_array('outside', $this->configuration['positions'], true)) { + $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($index); + if ($tokens[$prevNonWhitespaceIndex]->isComment()) { + continue; + } + + $tokens->removeLeadingWhitespace($index); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + $values = ['inside', 'outside']; + + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('positions', 'Whether spacing should be fixed inside and/or outside the offset braces.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset($values)]) + ->setDefault($values) + ->getOption(), + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php new file mode 100644 index 0000000..07ac05e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5. + * + * @author Marc Aubé + * @author Dariusz Rumiński + * + * @deprecated in favour of SpacesInsideParenthesisFixer + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoSpacesInsideParenthesisFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.', + [ + new CodeSample( + <<<'PHP' + proxyFixers); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isTokenKindFound('('); + } + + protected function createProxyFixers(): array + { + return [new SpacesInsideParenthesesFixer()]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php new file mode 100644 index 0000000..a8f1509 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶2.3. + * + * Don't add trailing spaces at the end of non-blank lines. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoTrailingWhitespaceFixer extends AbstractFixer +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'There must be no trailing whitespace at the end of non-blank lines.', + [new CodeSample("= 0; --$index) { + $token = $tokens[$index]; + if ( + $token->isGivenKind(\T_OPEN_TAG) + && $tokens->offsetExists($index + 1) + && $tokens[$index + 1]->isWhitespace() + && Preg::match('/(.*)\h$/', $token->getContent(), $openTagMatches) + && Preg::match('/^(\R)(.*)$/s', $tokens[$index + 1]->getContent(), $whitespaceMatches) + ) { + $tokens[$index] = new Token([\T_OPEN_TAG, $openTagMatches[1].$whitespaceMatches[1]]); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $whitespaceMatches[2]); + + continue; + } + + if (!$token->isWhitespace()) { + continue; + } + + $lines = Preg::split('/(\R+)/', $token->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE); + $linesSize = \count($lines); + + // fix only multiline whitespaces or singleline whitespaces at the end of file + if ($linesSize > 1 || !isset($tokens[$index + 1])) { + if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) || !Preg::match('/(.*)\R$/', $tokens[$index - 1]->getContent())) { + \assert(isset($lines[0])); + $lines[0] = rtrim($lines[0], " \t"); + } + + for ($i = 1; $i < $linesSize; ++$i) { + \assert(isset($lines[$i])); + $trimmedLine = rtrim($lines[$i], " \t"); + if ('' !== $trimmedLine) { + $lines[$i] = $trimmedLine; + } + } + + $content = implode('', $lines); + if ('' !== $content) { + $tokens[$index] = new Token([$token->getId(), $content]); + } else { + $tokens->clearAt($index); + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php new file mode 100644 index 0000000..f9887ac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NoWhitespaceInBlankLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Remove trailing whitespace at the end of blank lines.', + [new CodeSample("isWhitespace()) { + $this->fixWhitespaceToken($tokens, $i); + } + } + } + + private function fixWhitespaceToken(Tokens $tokens, int $index): void + { + $content = $tokens[$index]->getContent(); + $lines = Preg::split("/(\r\n|\n)/", $content); + $lineCount = \count($lines); + + if ( + // fix T_WHITESPACES with at least 3 lines (eg `\n \n`) + $lineCount > 2 + // and T_WHITESPACES with at least 2 lines at the end of file or after open tag with linebreak + || ($lineCount > 0 && (!isset($tokens[$index + 1]) || $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG))) + ) { + $lMax = isset($tokens[$index + 1]) ? $lineCount - 1 : $lineCount; + + $lStart = 1; + if ($tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) { + $lStart = 0; + } + + for ($l = $lStart; $l < $lMax; ++$l) { + \assert(isset($lines[$l])); + $lines[$l] = Preg::replace('/^\h+$/', '', $lines[$l]); + } + $content = implode($this->whitespacesConfig->getLineEnding(), $lines); + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php new file mode 100644 index 0000000..49f6cca --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * A file must always end with a line endings character. + * + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SingleBlankLineAtEofFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A PHP file without end tag must always end with a single empty line feed.', + [ + new CodeSample("count(); + + if ($count > 0 && !$tokens[$count - 1]->isGivenKind([\T_INLINE_HTML, \T_CLOSE_TAG, \T_OPEN_TAG])) { + $tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding()); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php new file mode 100644 index 0000000..88ff5ee --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php @@ -0,0 +1,245 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5. + * + * @phpstan-type _AutogeneratedInputConfiguration array{ + * space?: 'none'|'single', + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * space: 'none'|'single', + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Marc Aubé + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SpacesInsideParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Parentheses must be declared using the configured whitespace.', + [ + new CodeSample( + <<<'PHP' + 'none'], + ), + new CodeSample( + <<<'PHP' + 'single'], + ), + new CodeSample( + <<<'PHP' + 'single'], + ), + ], + 'By default there are not any additional spaces inside parentheses, however with `space=single` configuration option whitespace inside parentheses will be unified to single space.', + ); + } + + /** + * {@inheritdoc} + * + * Must run before FunctionToConstantFixer, GetClassToClassKeywordFixer, StringLengthToEmptyFixer. + * Must run after CombineConsecutiveIssetsFixer, CombineNestedDirnameFixer, IncrementStyleFixer, LambdaNotUsedImportFixer, ModernizeStrposFixer, NoUselessSprintfFixer, PowToExponentiationFixer. + */ + public function getPriority(): int + { + return 3; + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound(['(', CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + if ('none' === $this->configuration['space']) { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['(', [CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN]])) { + continue; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + // ignore parenthesis for T_ARRAY + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_ARRAY)) { + continue; + } + + $blockType = Tokens::detectBlockType($token); + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + + // remove space after opening `(` + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isComment()) { + $this->removeSpaceAroundToken($tokens, $index + 1); + } + + // remove space before closing `)` if it is not `list($a, $b, )` case + if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) { + $this->removeSpaceAroundToken($tokens, $endIndex - 1); + } + } + } + + if ('single' === $this->configuration['space']) { + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['(', [CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN]])) { + continue; + } + + $blockType = Tokens::detectBlockType($token); + $endParenthesisIndex = $tokens->findBlockEnd($blockType['type'], $index); + + // if not other content than spaces in block remove spaces + $blockContent = $this->getBlockContent($index, $endParenthesisIndex, $tokens); + if (1 === \count($blockContent) && \in_array(' ', $blockContent, true)) { + $this->removeSpaceAroundToken($tokens, $index + 1); + + continue; + } + + // don't process if the next token is `)` + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + if (')' === $tokens[$nextMeaningfulTokenIndex]->getContent()) { + continue; + } + + $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); + $afterParenthesisToken = $tokens[$afterParenthesisIndex]; + + if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { + $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); + $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $useStartParenthesisIndex); + + // add single-line edge whitespaces inside use parentheses + $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); + } + + // add single-line edge whitespaces inside parameters list parentheses + $this->fixParenthesisInnerEdge($tokens, $index, $endParenthesisIndex); + } + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Whether to have `single` or `none` space inside parentheses.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('none') + ->getOption(), + ]); + } + + /** + * Remove spaces from token at a given index. + */ + private function removeSpaceAroundToken(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if ($token->isWhitespace() && !str_contains($token->getContent(), "\n")) { + $tokens->clearAt($index); + } + } + + private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void + { + // fix white space before ')' + if ($tokens[$end - 1]->isWhitespace()) { + $content = $tokens[$end - 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($end - 1)]->isComment()) { + $tokens[$end - 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($end, new Token([\T_WHITESPACE, ' '])); + } + + // fix white space after '(' + if ($tokens[$start + 1]->isWhitespace()) { + $content = $tokens[$start + 1]->getContent(); + if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($start + 1)]->isComment()) { + $tokens[$start + 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($start + 1, new Token([\T_WHITESPACE, ' '])); + } + } + + /** + * @return list + */ + private function getBlockContent(int $startIndex, int $endIndex, Tokens $tokens): array + { + // + 1 for ( + $contents = []; + for ($i = ($startIndex + 1); $i < $endIndex; ++$i) { + $contents[] = $tokens[$i]->getContent(); + } + + return $contents; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php new file mode 100644 index 0000000..d0bbe43 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php @@ -0,0 +1,842 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\Fixer\IndentationTrait; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * stick_comment_to_next_continuous_control_statement?: bool, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * stick_comment_to_next_continuous_control_statement: bool, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StatementIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + use IndentationTrait; + + private const BLOCK_SIGNATURE_FIRST_TOKENS = [ + \T_USE, + \T_IF, + \T_ELSE, + \T_ELSEIF, + \T_FOR, + \T_FOREACH, + \T_WHILE, + \T_DO, + \T_SWITCH, + \T_CASE, + \T_DEFAULT, + \T_TRY, + \T_CLASS, + \T_INTERFACE, + \T_TRAIT, + \T_EXTENDS, + \T_IMPLEMENTS, + \T_CONST, + FCT::T_MATCH, + FCT::T_ENUM, + ]; + private const CONTROL_STRUCTURE_POSSIBIBLY_WITHOUT_BRACES_TOKENS = [ + \T_IF, + \T_ELSE, + \T_ELSEIF, + \T_FOR, + \T_FOREACH, + \T_WHILE, + \T_DO, + ]; + private const BLOCK_FIRST_TOKENS = ['{', [CT::T_DESTRUCTURING_BRACKET_OPEN], [CT::T_USE_TRAIT], [CT::T_GROUP_IMPORT_BRACE_OPEN], [CT::T_PROPERTY_HOOK_BRACE_OPEN], [FCT::T_ATTRIBUTE]]; + private const PROPERTY_KEYWORDS = [\T_VAR, \T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_STATIC, FCT::T_READONLY]; + + private AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer; + + private bool $bracesFixerCompatibility; + + public function __construct(bool $bracesFixerCompatibility = false) + { + parent::__construct(); + + $this->bracesFixerCompatibility = $bracesFixerCompatibility; + } + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Each statement must be indented.', + [ + new CodeSample( + <<<'PHP' + false], + ), + new CodeSample( + <<<'PHP' + true], + ), + ], + ); + } + + /** + * {@inheritdoc} + * + * Must run before HeredocIndentationFixer. + * Must run after BracesPositionFixer, ClassAttributesSeparationFixer, CurlyBracesPositionFixer, FullyQualifiedStrictTypesFixer, GlobalNamespaceImportFixer, MethodArgumentSpaceFixer, NoUselessElseFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority(): int + { + return -3; + } + + public function isCandidate(Tokens $tokens): bool + { + return true; + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('stick_comment_to_next_continuous_control_statement', 'Last comment of code block counts as comment for next block.')) + ->setAllowedTypes(['bool']) + ->setDefault(false) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $this->alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + + $endIndex = \count($tokens) - 1; + if ($tokens[$endIndex]->isWhitespace()) { + --$endIndex; + } + + $lastIndent = $this->getLineIndentationWithBracesCompatibility( + $tokens, + 0, + $this->extractIndent($this->computeNewLineContent($tokens, 0)), + ); + + /** + * @var list $scopes + */ + $scopes = [ + [ + 'type' => 'block', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $lastIndent, + 'is_indented_block' => false, + ], + ]; + + $previousLineInitialIndent = ''; + $previousLineNewIndent = ''; + $noBracesBlockStarts = []; + $alternativeBlockStarts = []; + $caseBlockStarts = []; + + foreach ($tokens as $index => $token) { + $currentScope = \count($scopes) - 1; + + if (isset($noBracesBlockStarts[$index])) { + $scopes[] = [ + 'type' => 'block', + 'skip' => false, + 'end_index' => $this->findStatementEndIndex($tokens, $index, \count($tokens) - 1) + 1, + 'end_index_inclusive' => true, + 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), + 'is_indented_block' => true, + ]; + ++$currentScope; + } + + if ( + $token->equalsAny(self::BLOCK_FIRST_TOKENS) + || ($token->equals('(') && !$tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_ARRAY)) + || isset($alternativeBlockStarts[$index]) + || isset($caseBlockStarts[$index]) + ) { + $endIndexInclusive = true; + + if ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { + $endIndex = $tokens->getNextTokenOfKind($index, ['{']); + } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { + $endIndex = $tokens->getNextTokenOfKind($index, [';']); + } elseif ($token->equals(':')) { + if (isset($caseBlockStarts[$index])) { + [$endIndex, $endIndexInclusive] = $this->findCaseBlockEnd($tokens, $index); + } elseif ($this->alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + $endIndex = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $alternativeBlockStarts[$index]); + } + } elseif ($token->isGivenKind(CT::T_DESTRUCTURING_BRACKET_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_DESTRUCTURING_BRACKET_CLOSE]]); + } elseif ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]); + } elseif ($token->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + } elseif ($token->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + } elseif ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_PROPERTY_HOOK_BRACE_CLOSE]]); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + + if ('block_signature' === $scopes[$currentScope]['type']) { + $initialIndent = $scopes[$currentScope]['initial_indent']; + } else { + $initialIndent = $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent); + } + + $skip = false; + if ($this->bracesFixerCompatibility) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (null !== $prevIndex) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FUNCTION, \T_FN])) { + $skip = true; + } + } + + $scopes[] = [ + 'type' => 'block', + 'skip' => $skip, + 'end_index' => $endIndex, + 'end_index_inclusive' => $endIndexInclusive, + 'initial_indent' => $initialIndent, + 'is_indented_block' => true, + ]; + ++$currentScope; + + while ($index >= $scopes[$currentScope]['end_index']) { + array_pop($scopes); + + --$currentScope; + } + + continue; + } + + if ( + $token->isGivenKind(CT::T_ARRAY_BRACKET_OPEN) + || ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_ARRAY)) + ) { + $blockType = $token->equals('(') ? Tokens::BLOCK_TYPE_PARENTHESIS : Tokens::BLOCK_TYPE_ARRAY_BRACKET; + + $scopes[] = [ + 'type' => 'statement', + 'skip' => true, + 'end_index' => $tokens->findBlockEnd($blockType, $index), + 'end_index_inclusive' => true, + 'initial_indent' => $previousLineInitialIndent, + 'new_indent' => $previousLineNewIndent, + 'is_indented_block' => false, + ]; + + continue; + } + + $isPropertyStart = $this->isPropertyStart($tokens, $index); + if ($isPropertyStart || $token->isGivenKind(self::BLOCK_SIGNATURE_FIRST_TOKENS)) { + $lastWhitespaceIndex = null; + $closingParenthesisIndex = null; + + for ($endIndex = $index + 1, $max = \count($tokens); $endIndex < $max; ++$endIndex) { + $endToken = $tokens[$endIndex]; + + if ($endToken->equals('(')) { + $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $endIndex); + $endIndex = $closingParenthesisIndex; + + continue; + } + + if ($endToken->isGivenKind(CT::T_ARRAY_BRACKET_OPEN)) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_BRACKET, $endIndex); + + continue; + } + + if ($endToken->equalsAny(['{', ';', [\T_DOUBLE_ARROW], [\T_IMPLEMENTS]])) { + break; + } + + if ($endToken->equals(':')) { + if ($token->isGivenKind([\T_CASE, \T_DEFAULT])) { + $caseBlockStarts[$endIndex] = $index; + } else { + $alternativeBlockStarts[$endIndex] = $index; + } + + break; + } + + if (!$token->isGivenKind(self::CONTROL_STRUCTURE_POSSIBIBLY_WITHOUT_BRACES_TOKENS)) { + continue; + } + + if ($endToken->isWhitespace()) { + $lastWhitespaceIndex = $endIndex; + + continue; + } + + if (!$endToken->isComment()) { + $noBraceBlockStartIndex = $lastWhitespaceIndex ?? $endIndex; + $noBracesBlockStarts[$noBraceBlockStartIndex] = true; + + $endIndex = $closingParenthesisIndex ?? $index; + + break; + } + } + + $scopes[] = [ + 'type' => 'block_signature', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), + 'is_indented_block' => $isPropertyStart || $token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS, \T_CONST, \T_CASE]), + ]; + + continue; + } + + if ($token->isGivenKind(\T_FUNCTION)) { + $endIndex = $index + 1; + + for ($max = \count($tokens); $endIndex < $max; ++$endIndex) { + if ($tokens[$endIndex]->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $endIndex); + + continue; + } + + if ($tokens[$endIndex]->equalsAny(['{', ';'])) { + break; + } + } + + $scopes[] = [ + 'type' => 'block_signature', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => true, + 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), + 'is_indented_block' => false, + ]; + + continue; + } + + if ( + $token->isWhitespace() + || ($index > 0 && $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) + ) { + $previousOpenTagContent = $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) + ? Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()) + : ''; + + $content = $previousOpenTagContent.($token->isWhitespace() ? $token->getContent() : ''); + + if (!Preg::match('/\R/', $content)) { + continue; + } + + $nextToken = $tokens[$index + 1] ?? null; + + if ( + $this->bracesFixerCompatibility + && null !== $nextToken + && $nextToken->isComment() + && !$this->isCommentWithFixableIndentation($tokens, $index + 1) + ) { + continue; + } + + if ('block' === $scopes[$currentScope]['type'] || 'block_signature' === $scopes[$currentScope]['type']) { + $indent = false; + + if ($scopes[$currentScope]['is_indented_block']) { + $firstNonWhitespaceTokenIndex = null; + $nextNewlineIndex = null; + for ($searchIndex = $index + 1, $max = \count($tokens); $searchIndex < $max; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + + if (!$searchToken->isWhitespace()) { + if (null === $firstNonWhitespaceTokenIndex) { + $firstNonWhitespaceTokenIndex = $searchIndex; + } + + continue; + } + + if (Preg::match('/\R/', $searchToken->getContent())) { + $nextNewlineIndex = $searchIndex; + + break; + } + } + + $endIndex = $scopes[$currentScope]['end_index']; + + if (!$scopes[$currentScope]['end_index_inclusive']) { + ++$endIndex; + } + + if ( + (null !== $firstNonWhitespaceTokenIndex && $firstNonWhitespaceTokenIndex < $endIndex) + || (null !== $nextNewlineIndex && $nextNewlineIndex < $endIndex) + ) { + if ( + // do we touch whitespace directly before comment... + $tokens[$firstNonWhitespaceTokenIndex]->isGivenKind(\T_COMMENT) + // ...and afterwards, there is only comment or `}` + && $tokens[$tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('}') + ) { + if ( + // ... and the comment was only content in docblock + $tokens[$tokens->getPrevMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('{') + ) { + $indent = true; + } else { + // or it was dedicated comment for next control loop + // ^^ we need to check if there is a control group afterwards, and in that case don't make extra indent level + $nextIndex = $tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex); + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (null !== $nextNextIndex && $tokens[$nextNextIndex]->isGivenKind([\T_ELSE, \T_ELSEIF])) { + $indent = true !== $this->configuration['stick_comment_to_next_continuous_control_statement']; + } else { + $indent = true; + } + } + } else { + $indent = true; + } + } + } + + $previousLineInitialIndent = $this->extractIndent($content); + + if ($scopes[$currentScope]['skip']) { + $whitespaces = $previousLineInitialIndent; + } else { + $whitespaces = $scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''); + } + + $content = Preg::replace( + '/(\R+)\h*$/', + '$1'.$whitespaces, + $content, + ); + + $previousLineNewIndent = $this->extractIndent($content); + } else { + $content = Preg::replace( + '/(\R)'.$scopes[$currentScope]['initial_indent'].'(\h*)$/D', + '$1'.$scopes[$currentScope]['new_indent'].'$2', + $content, + ); + } + + $lastIndent = $this->extractIndent($content); + + if ('' !== $previousOpenTagContent) { + $content = Preg::replace("/^{$previousOpenTagContent}/", '', $content); + } + + if ('' !== $content) { + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } elseif ($token->isWhitespace()) { + $tokens->clearAt($index); + } + + if (null !== $nextToken && $nextToken->isComment()) { + $tokens[$index + 1] = new Token([ + $nextToken->getId(), + Preg::replace( + '/(\R)'.preg_quote($previousLineInitialIndent, '/').'(\h*\S+.*)/', + '$1'.$previousLineNewIndent.'$2', + $nextToken->getContent(), + ), + ]); + } + + if ($token->isWhitespace()) { + continue; + } + } + + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + + while ($index >= $scopes[$currentScope]['end_index']) { + array_pop($scopes); + + if ([] === $scopes) { + return; + } + + --$currentScope; + } + + if ($token->isComment() || $token->equalsAny([';', ',', '}', [\T_OPEN_TAG], [\T_CLOSE_TAG], [CT::T_ATTRIBUTE_CLOSE]])) { + continue; + } + + if ('statement' !== $scopes[$currentScope]['type'] && 'block_signature' !== $scopes[$currentScope]['type']) { + $endIndex = $this->findStatementEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); + + if ($endIndex === $index) { + continue; + } + + $scopes[] = [ + 'type' => 'statement', + 'skip' => false, + 'end_index' => $endIndex, + 'end_index_inclusive' => false, + 'initial_indent' => $previousLineInitialIndent, + 'new_indent' => $previousLineNewIndent, + 'is_indented_block' => true, + ]; + } + } + } + + private function findStatementEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int + { + $endIndex = null; + + $ifLevel = 0; + $doWhileLevel = 0; + for ($searchEndIndex = $index; $searchEndIndex <= $parentScopeEndIndex; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + + if ( + $searchEndToken->isGivenKind(\T_IF) + && !$tokens[$tokens->getPrevMeaningfulToken($searchEndIndex)]->isGivenKind(\T_ELSE) + ) { + ++$ifLevel; + + continue; + } + + if ($searchEndToken->isGivenKind(\T_DO)) { + ++$doWhileLevel; + + continue; + } + + if ($searchEndToken->equalsAny(['(', '{', [CT::T_ARRAY_BRACKET_OPEN]])) { + if ($searchEndToken->equals('(')) { + $blockType = Tokens::BLOCK_TYPE_PARENTHESIS; + } elseif ($searchEndToken->equals('{')) { + $blockType = Tokens::BLOCK_TYPE_BRACE; + } else { + $blockType = Tokens::BLOCK_TYPE_ARRAY_BRACKET; + } + + $searchEndIndex = $tokens->findBlockEnd($blockType, $searchEndIndex); + $searchEndToken = $tokens[$searchEndIndex]; + } + + if (!$searchEndToken->equalsAny([';', ',', '}', [\T_CLOSE_TAG]])) { + continue; + } + + $controlStructureContinuationIndex = $tokens->getNextMeaningfulToken($searchEndIndex); + + if ( + $ifLevel > 0 + && null !== $controlStructureContinuationIndex + && $tokens[$controlStructureContinuationIndex]->isGivenKind([\T_ELSE, \T_ELSEIF]) + ) { + if ( + $tokens[$controlStructureContinuationIndex]->isGivenKind(\T_ELSE) + && !$tokens[$tokens->getNextMeaningfulToken($controlStructureContinuationIndex)]->isGivenKind(\T_IF) + ) { + --$ifLevel; + } + + $searchEndIndex = $controlStructureContinuationIndex; + + continue; + } + + if ( + $doWhileLevel > 0 + && null !== $controlStructureContinuationIndex + && $tokens[$controlStructureContinuationIndex]->isGivenKind(\T_WHILE) + ) { + --$doWhileLevel; + $searchEndIndex = $controlStructureContinuationIndex; + + continue; + } + + $endIndex = $tokens->getPrevNonWhitespace($searchEndIndex); + + break; + } + + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } + + /** + * @return array{int, bool} + */ + private function findCaseBlockEnd(Tokens $tokens, int $index): array + { + for ($max = \count($tokens); $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(\T_SWITCH)) { + $braceIndex = $tokens->getNextMeaningfulToken( + $tokens->findBlockEnd( + Tokens::BLOCK_TYPE_PARENTHESIS, + $tokens->getNextMeaningfulToken($index), + ), + ); + + if ($tokens[$braceIndex]->equals(':')) { + $index = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $index); + } else { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $braceIndex); + } + + continue; + } + + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + continue; + } + + if ($tokens[$index]->isGivenKind([\T_CASE, \T_DEFAULT])) { + return [$index, true]; + } + + if ($tokens[$index]->equalsAny(['}', [\T_ENDSWITCH]])) { + return [$tokens->getPrevNonWhitespace($index), false]; + } + } + + throw new \LogicException('End of case block not found.'); + } + + private function getLineIndentationWithBracesCompatibility(Tokens $tokens, int $index, string $regularIndent): string + { + if ( + $this->bracesFixerCompatibility + && $tokens[$index]->isGivenKind(\T_OPEN_TAG) + && Preg::match('/\R/', $tokens[$index]->getContent()) + && isset($tokens[$index + 1]) + && $tokens[$index + 1]->isWhitespace() + && Preg::match('/\h+$/D', $tokens[$index + 1]->getContent()) + ) { + return Preg::replace('/.*?(\h+)$/sD', '$1', $tokens[$index + 1]->getContent()); + } + + return $regularIndent; + } + + /** + * Returns whether the token at given index is the last token in a property + * declaration before the type or the name of that property. + */ + private function isPropertyStart(Tokens $tokens, int $index): bool + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ( + null === $nextIndex + || $tokens[$nextIndex]->isGivenKind(self::PROPERTY_KEYWORDS) + || $tokens[$nextIndex]->isGivenKind([\T_CONST, \T_FUNCTION]) + ) { + return false; + } + + while ($tokens[$index]->isGivenKind(self::PROPERTY_KEYWORDS)) { + if ($tokens[$index]->isGivenKind([\T_VAR, \T_PUBLIC, \T_PROTECTED, \T_PRIVATE])) { + return true; + } + + $index = $tokens->getPrevMeaningfulToken($index); + } + + return false; + } + + /** + * Returns whether the token at given index is a comment whose indentation + * can be fixed. + * + * Indentation of a comment is not changed when the comment is part of a + * multi-line message whose lines are all single-line comments and at least + * one line has meaningful content. + */ + private function isCommentWithFixableIndentation(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isComment()) { + return false; + } + + if (str_starts_with($tokens[$index]->getContent(), '/*')) { + return true; + } + + $indent = preg_quote($this->whitespacesConfig->getIndent(), '~'); + + if (Preg::match("~^(//|#)({$indent}.*)?$~", $tokens[$index]->getContent())) { + return false; + } + + $firstCommentIndex = $index; + while (true) { + $firstCommentCandidateIndex = $this->getSiblingContinuousSingleLineComment($tokens, $firstCommentIndex, false); + if (null === $firstCommentCandidateIndex) { + break; + } + + $firstCommentIndex = $firstCommentCandidateIndex; + } + + $lastCommentIndex = $index; + while (true) { + $lastCommentCandidateIndex = $this->getSiblingContinuousSingleLineComment($tokens, $lastCommentIndex, true); + if (null === $lastCommentCandidateIndex) { + break; + } + + $lastCommentIndex = $lastCommentCandidateIndex; + } + + if ($firstCommentIndex === $lastCommentIndex) { + return true; + } + + for ($i = $firstCommentIndex + 1; $i < $lastCommentIndex; ++$i) { + if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) { + return false; + } + } + + return true; + } + + private function getSiblingContinuousSingleLineComment(Tokens $tokens, int $index, bool $after): ?int + { + $siblingIndex = $index; + do { + if ($after) { + $siblingIndex = $tokens->getNextTokenOfKind($siblingIndex, [[\T_COMMENT]]); + } else { + $siblingIndex = $tokens->getPrevTokenOfKind($siblingIndex, [[\T_COMMENT]]); + } + + if (null === $siblingIndex) { + return null; + } + } while (str_starts_with($tokens[$siblingIndex]->getContent(), '/*')); + + $newLines = 0; + for ($i = min($siblingIndex, $index) + 1, $max = max($siblingIndex, $index); $i < $max; ++$i) { + if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) { + if (1 === $newLines || Preg::match('/\R.*\R/', $tokens[$i]->getContent())) { + return null; + } + + ++$newLines; + } + } + + return $siblingIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php new file mode 100644 index 0000000..33a9ad5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php @@ -0,0 +1,265 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Future; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * elements?: list<'constant'|'function'|'property'>, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * elements: list<'constant'|'function'|'property'>, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @author Dariusz Rumiński + * @author John Paul E. Balandan, CPA + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeDeclarationSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, \T_FINAL, FCT::T_READONLY, FCT::T_PUBLIC_SET, FCT::T_PROTECTED_SET, FCT::T_PRIVATE_SET]; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'Ensure single space between a variable and its type declaration in function arguments and properties.', + [ + new CodeSample( + <<<'PHP' + (string) $c; + } + } + + PHP, + ['elements' => ['function']], + ), + new CodeSample( + <<<'PHP' + ['property']], + ), + new VersionSpecificCodeSample( + <<<'PHP' + ['constant']], + ), + ], + ); + } + + public function isCandidate(Tokens $tokens): bool + { + return $tokens->isAnyTokenKindsFound([...Token::getClassyTokenKinds(), \T_FN, \T_FUNCTION]); + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('elements', 'Structural elements where the spacing after the type declaration should be fixed.')) + ->setAllowedTypes(['string[]']) + ->setAllowedValues([new AllowedValueSubset(['function', 'property', 'constant'])]) + ->setDefault( + Future::getV4OrV3(['function', 'property', 'constant'], ['function', 'property']), + ) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + + foreach (array_reverse($this->getElements($tokens), true) as $index => $type) { + if ('property' === $type && \in_array('property', $this->configuration['elements'], true)) { + $this->ensureSingleSpaceAtPropertyTypehint($tokens, $index); + + continue; + } + + if ('method' === $type && \in_array('function', $this->configuration['elements'], true)) { + $this->ensureSingleSpaceAtFunctionArgumentTypehint($functionsAnalyzer, $tokens, $index); + + continue; + } + + if ('const' === $type && \in_array('constant', $this->configuration['elements'], true)) { + $this->ensureSingleSpaceAtConstantTypehint($tokens, $index); + + // implicit continue; + } + } + } + + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens): array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + + $elements = array_map( + static fn (array $element): string => $element['type'], + array_filter( + $tokensAnalyzer->getClassyElements(), + static fn (array $element): bool => \in_array($element['type'], ['method', 'property', 'const'], true), + ), + ); + + foreach ($tokens as $index => $token) { + if ( + $token->isGivenKind(\T_FN) + || ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) + ) { + $elements[$index] = 'method'; + } + } + + return $elements; + } + + private function ensureSingleSpaceAtFunctionArgumentTypehint(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void + { + foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index)) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + + if (null === $argumentType) { + continue; + } + + $tokens->ensureWhitespaceAtIndex($argumentType->getEndIndex() + 1, 0, ' '); + } + } + + private function ensureSingleSpaceAtPropertyTypehint(Tokens $tokens, int $index): void + { + $propertyIndex = $index; + + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS)); + + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + + if (null === $propertyType) { + return; + } + + $tokens->ensureWhitespaceAtIndex($propertyType->getEndIndex() + 1, 0, ' '); + } + + private function ensureSingleSpaceAtConstantTypehint(Tokens $tokens, int $index): void + { + $constIndex = $index; + $equalsIndex = $tokens->getNextTokenOfKind($constIndex, ['=']); + + if (null === $equalsIndex) { + return; + } + + $nameIndex = $tokens->getPrevMeaningfulToken($equalsIndex); + + if (!$tokens[$nameIndex]->isGivenKind(\T_STRING)) { + return; + } + + $typeEndIndex = $tokens->getPrevMeaningfulToken($nameIndex); + + if (null === $typeEndIndex || $tokens[$typeEndIndex]->isGivenKind(\T_CONST)) { + return; + } + + $tokens->ensureWhitespaceAtIndex($typeEndIndex + 1, 0, ' '); + } + + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php new file mode 100644 index 0000000..5820c69 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php @@ -0,0 +1,175 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ConfigurableFixerTrait; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @phpstan-type _AutogeneratedInputConfiguration array{ + * space?: 'none'|'single', + * space_multiple_catch?: 'none'|'single'|null, + * } + * @phpstan-type _AutogeneratedComputedConfiguration array{ + * space: 'none'|'single', + * space_multiple_catch: 'none'|'single'|null, + * } + * + * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypesSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ + use ConfigurableFixerTrait; + + public function getDefinition(): FixerDefinitionInterface + { + return new FixerDefinition( + 'A single space or none should be around union type and intersection type operators.', + [ + new CodeSample( + " 'single'], + ), + new VersionSpecificCodeSample( + "isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + + protected function configurePostNormalisation(): void + { + if (!isset($this->configuration['space_multiple_catch'])) { + $this->configuration = [ + 'space' => $this->configuration['space'], + 'space_multiple_catch' => $this->configuration['space'], + ]; + } + } + + protected function createConfigurationDefinition(): FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([ + (new FixerOptionBuilder('space', 'Spacing to apply around union type and intersection type operators.')) + ->setAllowedValues(['none', 'single']) + ->setDefault('none') + ->getOption(), + (new FixerOptionBuilder('space_multiple_catch', 'Spacing to apply around type operator when catching exceptions of multiple types, use `null` to follow the value configured for `space`.')) + ->setAllowedValues(['none', 'single', null]) + ->setDefault(null) + ->getOption(), + ]); + } + + protected function applyFix(\SplFileInfo $file, Tokens $tokens): void + { + $tokenCount = $tokens->count() - 1; + + for ($index = 0; $index < $tokenCount; ++$index) { + if ($tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space']); + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_CATCH)) { + while (true) { + $index = $tokens->getNextTokenOfKind($index, [')', [CT::T_TYPE_ALTERNATION]]); + + if ($tokens[$index]->equals(')')) { + break; + } + + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space_multiple_catch']); + } + + // implicit continue + } + } + } + + private function fixSpacing(Tokens $tokens, int $index, bool $singleSpace): int + { + if (!$singleSpace) { + $this->ensureNoSpace($tokens, $index + 1); + $this->ensureNoSpace($tokens, $index - 1); + + return 0; + } + + $addedTokenCount = 0; + $addedTokenCount += $this->ensureSingleSpace($tokens, $index + 1, 0); + $addedTokenCount += $this->ensureSingleSpace($tokens, $index - 1, 1); + + return $addedTokenCount; + } + + private function ensureSingleSpace(Tokens $tokens, int $index, int $offset): int + { + if (!$tokens[$index]->isWhitespace()) { + $tokens->insertSlices([$index + $offset => new Token([\T_WHITESPACE, ' '])]); + + return 1; + } + + if (' ' !== $tokens[$index]->getContent() && !Preg::match('/\R/', $tokens[$index]->getContent())) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + + return 0; + } + + private function ensureNoSpace(Tokens $tokens, int $index): void + { + if ($tokens[$index]->isWhitespace() && !Preg::match('/\R/', $tokens[$index]->getContent())) { + $tokens->clearAt($index); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php new file mode 100644 index 0000000..bd14c0e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\WhitespacesFixerConfig; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface WhitespacesAwareFixerInterface extends FixerInterface +{ + public function setWhitespacesConfig(WhitespacesFixerConfig $config): void; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php new file mode 100644 index 0000000..290eb7d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AliasedFixerOption implements FixerOptionInterface +{ + private FixerOptionInterface $fixerOption; + + private string $alias; + + public function __construct(FixerOptionInterface $fixerOption, string $alias) + { + $this->fixerOption = $fixerOption; + $this->alias = $alias; + } + + public function getAlias(): string + { + return $this->alias; + } + + public function getName(): string + { + return $this->fixerOption->getName(); + } + + public function getDescription(): string + { + return $this->fixerOption->getDescription(); + } + + public function hasDefault(): bool + { + return $this->fixerOption->hasDefault(); + } + + /** + * @return mixed + * + * @throws \LogicException when no default value is defined + */ + public function getDefault() + { + return $this->fixerOption->getDefault(); + } + + public function getAllowedTypes(): ?array + { + return $this->fixerOption->getAllowedTypes(); + } + + public function getAllowedValues(): ?array + { + return $this->fixerOption->getAllowedValues(); + } + + public function getNormalizer(): ?\Closure + { + return $this->fixerOption->getNormalizer(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php new file mode 100644 index 0000000..8b75316 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AliasedFixerOptionBuilder +{ + private FixerOptionBuilder $optionBuilder; + + private string $alias; + + public function __construct(FixerOptionBuilder $optionBuilder, string $alias) + { + $this->optionBuilder = $optionBuilder; + $this->alias = $alias; + } + + /** + * @param mixed $default + */ + public function setDefault($default): self + { + $this->optionBuilder->setDefault($default); + + return $this; + } + + /** + * @param list $allowedTypes + */ + public function setAllowedTypes(array $allowedTypes): self + { + $this->optionBuilder->setAllowedTypes($allowedTypes); + + return $this; + } + + /** + * @param non-empty-list $allowedValues + */ + public function setAllowedValues(array $allowedValues): self + { + $this->optionBuilder->setAllowedValues($allowedValues); + + return $this; + } + + public function setNormalizer(\Closure $normalizer): self + { + $this->optionBuilder->setNormalizer($normalizer); + + return $this; + } + + public function getOption(): AliasedFixerOption + { + return new AliasedFixerOption( + $this->optionBuilder->getOption(), + $this->alias, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php new file mode 100644 index 0000000..88aa905 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AllowedValueSubset +{ + /** + * @var non-empty-list + */ + private array $allowedValues; + + /** + * @param non-empty-list $allowedValues + */ + public function __construct(array $allowedValues) + { + sort($allowedValues, \SORT_FLAG_CASE | \SORT_STRING); + $this->allowedValues = $allowedValues; + } + + /** + * Checks whether the given values are a subset of the allowed ones. + * + * @param mixed $values the value to validate + */ + public function __invoke($values): bool + { + if (!\is_array($values)) { + return false; + } + + foreach ($values as $value) { + if (!\in_array($value, $this->allowedValues, true)) { + return false; + } + } + + return true; + } + + /** + * @return non-empty-list + */ + public function getAllowedValues(): array + { + return $this->allowedValues; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php new file mode 100644 index 0000000..8f85554 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DeprecatedFixerOption implements DeprecatedFixerOptionInterface +{ + private FixerOptionInterface $option; + + private string $deprecationMessage; + + public function __construct(FixerOptionInterface $option, string $deprecationMessage) + { + $this->option = $option; + $this->deprecationMessage = $deprecationMessage; + } + + public function getName(): string + { + return $this->option->getName(); + } + + public function getDescription(): string + { + return $this->option->getDescription(); + } + + public function hasDefault(): bool + { + return $this->option->hasDefault(); + } + + /** + * @return mixed + */ + public function getDefault() + { + return $this->option->getDefault(); + } + + public function getAllowedTypes(): ?array + { + return $this->option->getAllowedTypes(); + } + + public function getAllowedValues(): ?array + { + return $this->option->getAllowedValues(); + } + + public function getNormalizer(): ?\Closure + { + return $this->option->getNormalizer(); + } + + public function getDeprecationMessage(): string + { + return $this->deprecationMessage; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php new file mode 100644 index 0000000..36cf496 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface DeprecatedFixerOptionInterface extends FixerOptionInterface +{ + public function getDeprecationMessage(): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php new file mode 100644 index 0000000..8df8847 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +use PhpCsFixer\Future; +use PhpCsFixer\Preg; +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use Symfony\Component\OptionsResolver\OptionsResolver; + +/** + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerConfigurationResolver implements FixerConfigurationResolverInterface +{ + /** + * @var list + * + * @readonly + */ + private array $options; + + /** + * @param iterable $options + */ + public function __construct(iterable $options) + { + $fixerOptionSorter = new FixerOptionSorter(); + $this->validateOptions($options); + + $this->options = $fixerOptionSorter->sort($options); + + if (0 === \count($this->options)) { + throw new \LogicException('Options cannot be empty.'); + } + } + + public function getOptions(): array + { + return $this->options; + } + + public function resolve(array $configuration): array + { + $resolver = new OptionsResolver(); + + foreach ($this->options as $option) { + $name = $option->getName(); + + if ($option instanceof AliasedFixerOption) { + $alias = $option->getAlias(); + + if (\array_key_exists($alias, $configuration)) { + if (\array_key_exists($name, $configuration)) { + throw new InvalidOptionsException(\sprintf('Aliased option "%s"/"%s" is passed multiple times.', $name, $alias)); + } + + Future::triggerDeprecation(new \RuntimeException(\sprintf( + 'Option "%s" is deprecated, use "%s" instead.', + $alias, + $name, + ))); + + $configuration[$name] = $configuration[$alias]; + unset($configuration[$alias]); + } + } + + if ($option->hasDefault()) { + $resolver->setDefault($name, $option->getDefault()); + } else { + $resolver->setRequired($name); + } + + $allowedValues = $option->getAllowedValues(); + if (null !== $allowedValues) { + foreach ($allowedValues as &$allowedValue) { + if (\is_object($allowedValue) && \is_callable($allowedValue)) { + $allowedValue = static fn (/* mixed */ $values) => $allowedValue($values); + } + } + + $resolver->setAllowedValues($name, $allowedValues); + } + + $allowedTypes = $option->getAllowedTypes(); + if (null !== $allowedTypes) { + $allowedTypesNormalised = array_map( + static function (string $type): string { + // Symfony OptionsResolver doesn't support `array` natively, let's simplify the type + $matches = []; + if (true === Preg::match('/array<\w+,\s*(\??[\w\'|]+)>/', $type, $matches)) { + if ('?' === $matches[1][0]) { + return 'array'; + } + + if ("'" === $matches[1][0]) { + return 'string[]'; + } + + return $matches[1].'[]'; + } + + // Symfony OptionsResolver doesn't support 'class-string' natively, let's simplify the type + return str_replace('class-string', 'string', $type); + }, + $allowedTypes, + ); + + $resolver->setAllowedTypes($name, $allowedTypesNormalised); + } + + $normalizer = $option->getNormalizer(); + if (null !== $normalizer) { + $resolver->setNormalizer($name, $normalizer); + } + } + + return $resolver->resolve($configuration); + } + + /** + * @param iterable $options + * + * @throws \LogicException when the option is already defined + */ + private function validateOptions(iterable $options): void + { + $names = []; + + foreach ($options as $option) { + $name = $option->getName(); + + if (\in_array($name, $names, true)) { + throw new \LogicException(\sprintf('The "%s" option is defined multiple times.', $name)); + } + + $names[] = $name; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php new file mode 100644 index 0000000..61761fc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FixerConfigurationResolverInterface +{ + /** + * @return list + */ + public function getOptions(): array; + + /** + * @param array $configuration + * + * @return array + */ + public function resolve(array $configuration): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php new file mode 100644 index 0000000..4e35765 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerOption implements FixerOptionInterface +{ + private string $name; + + private string $description; + + private bool $isRequired; + + /** + * @var mixed + */ + private $default; + + /** + * @var null|list + */ + private ?array $allowedTypes; + + /** + * @var null|non-empty-list + */ + private ?array $allowedValues; + + private ?\Closure $normalizer; + + /** + * @param mixed $default + * @param null|list $allowedTypes + * @param null|non-empty-list $allowedValues + */ + public function __construct( + string $name, + string $description, + bool $isRequired = true, + $default = null, + ?array $allowedTypes = null, + ?array $allowedValues = null, + ?\Closure $normalizer = null + ) { + if ($isRequired && null !== $default) { + throw new \LogicException('Required options cannot have a default value.'); + } + + if (null !== $allowedValues) { + $allowedValues = array_map( + fn ($allowedValue) => $allowedValue instanceof \Closure ? $this->unbind($allowedValue) : $allowedValue, + $allowedValues, + ); + } + + $this->name = $name; + $this->description = $description; + $this->isRequired = $isRequired; + $this->default = $default; + $this->allowedTypes = $allowedTypes; + $this->allowedValues = $allowedValues; + + if (null !== $normalizer) { + $this->normalizer = $this->unbind($normalizer); + } else { + $this->normalizer = null; + } + } + + public function getName(): string + { + return $this->name; + } + + public function getDescription(): string + { + return $this->description; + } + + public function hasDefault(): bool + { + return !$this->isRequired; + } + + /** + * @return mixed + */ + public function getDefault() + { + if (!$this->hasDefault()) { + throw new \LogicException('No default value defined.'); + } + + return $this->default; + } + + public function getAllowedTypes(): ?array + { + return $this->allowedTypes; + } + + public function getAllowedValues(): ?array + { + return $this->allowedValues; + } + + public function getNormalizer(): ?\Closure + { + return $this->normalizer; + } + + /** + * Unbinds the given closure to avoid memory leaks. + * + * The closures provided to this class were probably defined in a fixer + * class and thus bound to it by default. The configuration will then be + * stored in {@see AbstractFixer::$configurationDefinition}, leading to the + * following cyclic reference: + * + * fixer -> configuration definition -> options -> closures -> fixer + * + * This cyclic reference prevent the garbage collector to free memory as + * all elements are still referenced. + * + * See {@see https://bugs.php.net/bug.php?id=69639 Bug #69639} for details. + */ + private function unbind(\Closure $closure): \Closure + { + return $closure->bindTo(null); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php new file mode 100644 index 0000000..d3413a5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerOptionBuilder +{ + private string $name; + + private string $description; + + /** + * @var null|mixed + */ + private $default; + + private bool $isRequired = true; + + /** + * @var null|list + */ + private ?array $allowedTypes = null; + + /** + * @var null|non-empty-list + */ + private ?array $allowedValues = null; + + private ?\Closure $normalizer = null; + + private ?string $deprecationMessage = null; + + public function __construct(string $name, string $description) + { + $this->name = $name; + $this->description = $description; + $this->default = null; + } + + /** + * @param mixed $default + * + * @return $this + */ + public function setDefault($default): self + { + $this->default = $default; + $this->isRequired = false; + + return $this; + } + + /** + * @param list $allowedTypes + * + * @return $this + */ + public function setAllowedTypes(array $allowedTypes): self + { + $this->allowedTypes = $allowedTypes; + + return $this; + } + + /** + * @param non-empty-list $allowedValues + * + * @return $this + */ + public function setAllowedValues(array $allowedValues): self + { + $this->allowedValues = $allowedValues; + + return $this; + } + + /** + * @return $this + */ + public function setNormalizer(\Closure $normalizer): self + { + $this->normalizer = $normalizer; + + return $this; + } + + /** + * @return $this + */ + public function setDeprecationMessage(?string $deprecationMessage): self + { + $this->deprecationMessage = $deprecationMessage; + + return $this; + } + + public function getOption(): FixerOptionInterface + { + $option = new FixerOption( + $this->name, + $this->description, + $this->isRequired, + $this->default, + $this->allowedTypes, + $this->allowedValues, + $this->normalizer, + ); + + if (null !== $this->deprecationMessage) { + $option = new DeprecatedFixerOption($option, $this->deprecationMessage); + } + + return $option; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php new file mode 100644 index 0000000..35af494 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FixerOptionInterface +{ + public function getName(): string; + + public function getDescription(): string; + + public function hasDefault(): bool; + + /** + * @return mixed + * + * @throws \LogicException when no default value is defined + */ + public function getDefault(); + + /** + * @return null|list + */ + public function getAllowedTypes(): ?array; + + /** + * @return null|non-empty-list + */ + public function getAllowedValues(): ?array; + + public function getNormalizer(): ?\Closure; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php new file mode 100644 index 0000000..90b7fde --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionSorter.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerOptionSorter +{ + /** + * @param iterable $options + * + * @return list + */ + public function sort(iterable $options): array + { + if (!\is_array($options)) { + $options = iterator_to_array($options, false); + } + + usort($options, static fn (FixerOptionInterface $a, FixerOptionInterface $b): int => $a->getName() <=> $b->getName()); + + return $options; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php new file mode 100644 index 0000000..5355a44 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerConfiguration; + +use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class InvalidOptionsForEnvException extends InvalidOptionsException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php new file mode 100644 index 0000000..826374d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CodeSample implements CodeSampleInterface +{ + private string $code; + + /** + * @var null|array + */ + private ?array $configuration; + + /** + * @param null|array $configuration + */ + public function __construct(string $code, ?array $configuration = null) + { + $this->code = $code; + $this->configuration = $configuration; + } + + public function getCode(): string + { + return $this->code; + } + + public function getConfiguration(): ?array + { + return $this->configuration; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php new file mode 100644 index 0000000..0f8da2b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface CodeSampleInterface +{ + public function getCode(): string; + + /** + * @return null|array + */ + public function getConfiguration(): ?array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php new file mode 100644 index 0000000..ce2471d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileSpecificCodeSample implements FileSpecificCodeSampleInterface +{ + private CodeSampleInterface $codeSample; + + private \SplFileInfo $splFileInfo; + + /** + * @param null|array $configuration + */ + public function __construct( + string $code, + \SplFileInfo $splFileInfo, + ?array $configuration = null + ) { + $this->codeSample = new CodeSample($code, $configuration); + $this->splFileInfo = $splFileInfo; + } + + public function getCode(): string + { + return $this->codeSample->getCode(); + } + + public function getConfiguration(): ?array + { + return $this->codeSample->getConfiguration(); + } + + public function getSplFileInfo(): \SplFileInfo + { + return $this->splFileInfo; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php new file mode 100644 index 0000000..a7784de --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FileSpecificCodeSampleInterface extends CodeSampleInterface +{ + public function getSplFileInfo(): \SplFileInfo; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php new file mode 100644 index 0000000..408a785 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerDefinition implements FixerDefinitionInterface +{ + private string $summary; + + /** + * @var list + */ + private array $codeSamples; + + /** + * Description of Fixer and benefit of using it. + */ + private ?string $description; + + /** + * Description why Fixer is risky. + */ + private ?string $riskyDescription; + + /** + * @param list $codeSamples array of samples, where single sample is [code, configuration] + * @param null|string $riskyDescription null for non-risky fixer + */ + public function __construct( + string $summary, + array $codeSamples, + ?string $description = null, + ?string $riskyDescription = null + ) { + $this->summary = $summary; + $this->codeSamples = $codeSamples; + $this->description = $description; + $this->riskyDescription = $riskyDescription; + } + + public function getSummary(): string + { + return $this->summary; + } + + public function getDescription(): ?string + { + return $this->description; + } + + public function getRiskyDescription(): ?string + { + return $this->riskyDescription; + } + + public function getCodeSamples(): array + { + return $this->codeSamples; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php new file mode 100644 index 0000000..4e61ff6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface FixerDefinitionInterface +{ + public function getSummary(): string; + + public function getDescription(): ?string; + + /** + * @return null|string null for non-risky fixer + */ + public function getRiskyDescription(): ?string; + + /** + * Array of samples, where single sample is [code, configuration]. + * + * @return list + */ + public function getCodeSamples(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php new file mode 100644 index 0000000..ff60c6a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class VersionSpecificCodeSample implements VersionSpecificCodeSampleInterface +{ + private CodeSampleInterface $codeSample; + + private VersionSpecificationInterface $versionSpecification; + + /** + * @param null|array $configuration + */ + public function __construct( + string $code, + VersionSpecificationInterface $versionSpecification, + ?array $configuration = null + ) { + $this->codeSample = new CodeSample($code, $configuration); + $this->versionSpecification = $versionSpecification; + } + + public function getCode(): string + { + return $this->codeSample->getCode(); + } + + public function getConfiguration(): ?array + { + return $this->codeSample->getConfiguration(); + } + + public function isSuitableFor(int $version): bool + { + return $this->versionSpecification->isSatisfiedBy($version); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php new file mode 100644 index 0000000..ed2176f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface VersionSpecificCodeSampleInterface extends CodeSampleInterface +{ + public function isSuitableFor(int $version): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php new file mode 100644 index 0000000..bf951f4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class VersionSpecification implements VersionSpecificationInterface +{ + /** + * @var null|int<1, max> + */ + private ?int $minimum; + + /** + * @var null|int<1, max> + */ + private ?int $maximum; + + /** + * @param null|int<1, max> $minimum + * @param null|int<1, max> $maximum + * + * @throws \InvalidArgumentException + */ + public function __construct(?int $minimum = null, ?int $maximum = null) + { + if (null === $minimum && null === $maximum) { + throw new \InvalidArgumentException('Minimum or maximum need to be specified.'); + } + + if (null !== $minimum && 1 > $minimum) { + throw new \InvalidArgumentException('Minimum needs to be either null or an integer greater than 0.'); + } + + if (null !== $maximum) { + if (1 > $maximum) { + throw new \InvalidArgumentException('Maximum needs to be either null or an integer greater than 0.'); + } + + if (null !== $minimum && $maximum < $minimum) { + throw new \InvalidArgumentException('Maximum should not be lower than the minimum.'); + } + } + + $this->minimum = $minimum; + $this->maximum = $maximum; + } + + public function isSatisfiedBy(int $version): bool + { + if (null !== $this->minimum && $version < $this->minimum) { + return false; + } + + if (null !== $this->maximum && $version > $this->maximum) { + return false; + } + + return true; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php new file mode 100644 index 0000000..64548c2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface VersionSpecificationInterface +{ + public function isSatisfiedBy(int $version): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php new file mode 100644 index 0000000..a8e5159 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php @@ -0,0 +1,246 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\RuleSet\RuleSetInterface; +use Symfony\Component\Finder\Finder as SymfonyFinder; +use Symfony\Component\Finder\SplFileInfo; + +/** + * Class provides a way to create a group of fixers. + * + * Fixers may be registered (made the factory aware of them) by + * registering a custom fixer and default, built in fixers. + * Then, one can attach Config instance to fixer instances. + * + * Finally factory creates a ready to use group of fixers. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerFactory +{ + private FixerNameValidator $nameValidator; + + /** + * @var list + */ + private array $fixers = []; + + /** + * @var array + */ + private array $fixersByName = []; + + public function __construct() + { + $this->nameValidator = new FixerNameValidator(); + } + + public function setWhitespacesConfig(WhitespacesFixerConfig $config): self + { + foreach ($this->fixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + + return $this; + } + + /** + * @return list + */ + public function getFixers(): array + { + $this->fixers = Utils::sortFixers($this->fixers); + + return $this->fixers; + } + + /** + * @return $this + */ + public function registerBuiltInFixers(): self + { + static $builtInFixers = null; + + if (null === $builtInFixers) { + /** @var list> */ + $builtInFixers = []; + + $finder = SymfonyFinder::create()->files() + ->in(__DIR__.'/Fixer') + ->exclude(['Internal']) + ->name('*Fixer.php') + ->depth(1) + ; + + /** @var SplFileInfo $file */ + foreach ($finder as $file) { + $relativeNamespace = $file->getRelativePath(); + $fixerClass = 'PhpCsFixer\Fixer\\'.('' !== $relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); + $builtInFixers[] = $fixerClass; + } + } + + foreach ($builtInFixers as $class) { + /** @var FixerInterface */ + $fixer = new $class(); + $this->registerFixer($fixer, false); + } + + return $this; + } + + /** + * @param iterable $fixers + * + * @return $this + */ + public function registerCustomFixers(iterable $fixers): self + { + foreach ($fixers as $fixer) { + $this->registerFixer($fixer, true); + } + + return $this; + } + + /** + * @return $this + */ + public function registerFixer(FixerInterface $fixer, bool $isCustom): self + { + $name = $fixer->getName(); + + if (isset($this->fixersByName[$name])) { + throw new \UnexpectedValueException(\sprintf('Fixer named "%s" is already registered.', $name)); + } + + if (!$this->nameValidator->isValid($name, $isCustom)) { + throw new \UnexpectedValueException(\sprintf('Fixer named "%s" has invalid name.', $name)); + } + + $this->fixers[] = $fixer; + $this->fixersByName[$name] = $fixer; + + return $this; + } + + /** + * Apply RuleSet on fixers to filter out all unwanted fixers. + * + * @return $this + */ + public function useRuleSet(RuleSetInterface $ruleSet): self + { + $fixers = []; + $fixersByName = []; + $fixerConflicts = []; + + $fixerNames = array_keys($ruleSet->getRules()); + foreach ($fixerNames as $name) { + if (!\array_key_exists($name, $this->fixersByName)) { + throw new \UnexpectedValueException(\sprintf('Rule "%s" does not exist.', $name)); + } + + $fixer = $this->fixersByName[$name]; + $config = $ruleSet->getRuleConfiguration($name); + + if (null !== $config) { + if ($fixer instanceof ConfigurableFixerInterface) { + if (\count($config) < 1) { + throw new InvalidFixerConfigurationException($fixer->getName(), 'Configuration must be an array and may not be empty.'); + } + + $fixer->configure($config); + } else { + throw new InvalidFixerConfigurationException($fixer->getName(), 'Is not configurable.'); + } + } + + $fixers[] = $fixer; + $fixersByName[$name] = $fixer; + $conflicts = array_values(array_intersect($this->getFixersConflicts($fixer), $fixerNames)); + + if (\count($conflicts) > 0) { + $fixerConflicts[$name] = $conflicts; + } + } + + if (\count($fixerConflicts) > 0) { + throw new \UnexpectedValueException($this->generateConflictMessage($fixerConflicts)); + } + + $this->fixers = $fixers; + $this->fixersByName = $fixersByName; + + return $this; + } + + /** + * Check if fixer exists. + */ + public function hasRule(string $name): bool + { + return isset($this->fixersByName[$name]); + } + + /** + * @return list + */ + private function getFixersConflicts(FixerInterface $fixer): array + { + return [ + 'blank_lines_before_namespace' => [ + 'no_blank_lines_before_namespace', + 'single_blank_line_before_namespace', + ], + 'no_blank_lines_before_namespace' => ['single_blank_line_before_namespace'], + 'single_import_per_statement' => ['group_import'], + ][$fixer->getName()] ?? []; + } + + /** + * @param array> $fixerConflicts + */ + private function generateConflictMessage(array $fixerConflicts): string + { + $message = 'Rule contains conflicting fixers:'; + $report = []; + + foreach ($fixerConflicts as $fixer => $fixers) { + // filter mutual conflicts + $report[$fixer] = array_values(array_filter( + $fixers, + static fn (string $candidate): bool => !\array_key_exists($candidate, $report) || !\in_array($fixer, $report[$candidate], true), + )); + + if (\count($report[$fixer]) > 0) { + $message .= \sprintf("\n- \"%s\" with %s", $fixer, Utils::naturalLanguageJoin($report[$fixer])); + } + } + + return $message; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php new file mode 100644 index 0000000..e134c9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerNameValidator +{ + public function isValid(string $name, bool $isCustom): bool + { + if (!$isCustom) { + return Preg::match('/^[a-z][a-z0-9_]*$/', $name); + } + + return Preg::match('/^[A-Z][a-zA-Z0-9]*\/[a-z][a-z0-9_]*$/', $name); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Future.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Future.php new file mode 100644 index 0000000..0485bff --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Future.php @@ -0,0 +1,114 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Future +{ + private static bool $isFutureModeEnforced = false; + + /** + * @var array + */ + private static array $deprecations = []; + + private function __construct() + { + // cannot create instance + } + + /** + * @return mixed + */ + public static function runWithEnforcedFutureMode(callable $callback) + { + try { + self::$isFutureModeEnforced = true; + + return $callback(); + } finally { + self::$isFutureModeEnforced = false; + } + } + + public static function isFutureModeEnabled(): bool + { + return self::$isFutureModeEnforced || filter_var( + getenv('PHP_CS_FIXER_FUTURE_MODE'), + \FILTER_VALIDATE_BOOL, + ); + } + + public static function triggerDeprecation(\Exception $futureException): void + { + if (self::isFutureModeEnabled()) { + throw new \RuntimeException( + 'Your are using something deprecated, see previous exception. Aborting execution because `PHP_CS_FIXER_FUTURE_MODE` environment variable is set.', + 0, + $futureException, + ); + } + + $message = $futureException->getMessage(); + + self::$deprecations[$message] = true; + @trigger_error($message, \E_USER_DEPRECATED); + } + + /** + * @return list + */ + public static function getTriggeredDeprecations(): array + { + $triggeredDeprecations = array_keys(self::$deprecations); + sort($triggeredDeprecations); + + return $triggeredDeprecations; + } + + /** + * @template T + * + * @param T $new + * @param T $old + * + * @return T + * + * @TODO v4.0: remove this method, ensure code compiles, create getV5OrV4. While removing, ensure to document in `UPGRADE-vX.md` file. + */ + public static function getV4OrV3($new, $old) + { + return self::getNewOrOld($new, $old); + } + + /** + * @template T + * + * @param T $new + * @param T $old + * + * @return T + */ + private static function getNewOrOld($new, $old) + { + return self::isFutureModeEnabled() ? $new : $old; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Hasher.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Hasher.php new file mode 100644 index 0000000..236bf04 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Hasher.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Hasher +{ + private function __construct() + { + // cannot create instance of util. class + } + + /** + * @return non-empty-string + */ + public static function calculate(string $code): string + { + return \PHP_VERSION_ID >= 8_01_00 + ? hash('xxh128', $code) + : md5($code); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php new file mode 100644 index 0000000..4395a88 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use PhpCsFixer\Hasher; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CachingLinter implements LinterInterface +{ + private LinterInterface $sublinter; + + /** + * @var array + */ + private array $cache = []; + + public function __construct(LinterInterface $linter) + { + $this->sublinter = $linter; + } + + public function isAsync(): bool + { + return $this->sublinter->isAsync(); + } + + public function lintFile(string $path): LintingResultInterface + { + $checksum = Hasher::calculate(file_get_contents($path)); + + return $this->cache[$checksum] ??= $this->sublinter->lintFile($path); + } + + public function lintSource(string $source): LintingResultInterface + { + $checksum = Hasher::calculate($source); + + return $this->cache[$checksum] ??= $this->sublinter->lintSource($source); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php new file mode 100644 index 0000000..5fe267f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Handle PHP code linting process. + * + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Linter implements LinterInterface +{ + private LinterInterface $subLinter; + + public function __construct() + { + $this->subLinter = new TokenizerLinter(); + } + + public function isAsync(): bool + { + return $this->subLinter->isAsync(); + } + + public function lintFile(string $path): LintingResultInterface + { + return $this->subLinter->lintFile($path); + } + + public function lintSource(string $source): LintingResultInterface + { + return $this->subLinter->lintSource($source); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php new file mode 100644 index 0000000..883c71c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Interface for PHP code linting process manager. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface LinterInterface +{ + public function isAsync(): bool; + + /** + * Lint PHP file. + */ + public function lintFile(string $path): LintingResultInterface; + + /** + * Lint PHP code. + */ + public function lintSource(string $source): LintingResultInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php new file mode 100644 index 0000000..c2e1c85 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +class LintingException extends \RuntimeException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php new file mode 100644 index 0000000..ccac4ef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface LintingResultInterface +{ + /** + * Check if linting process was successful and raise LintingException if not. + */ + public function check(): void; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php new file mode 100644 index 0000000..ac50217 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php @@ -0,0 +1,153 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\FileRemoval; +use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Component\Process\PhpExecutableFinder; +use Symfony\Component\Process\Process; + +/** + * Handle PHP code linting using separated process of `php -l _file_`. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessLinter implements LinterInterface +{ + private FileRemoval $fileRemoval; + + private ProcessLinterProcessBuilder $processBuilder; + + /** + * Temporary file for code linting. + */ + private ?string $temporaryFile = null; + + /** + * @param null|string $executable PHP executable, null for autodetection + */ + public function __construct(?string $executable = null) + { + if (null === $executable) { + $executableFinder = new PhpExecutableFinder(); + $executable = $executableFinder->find(false); + + if (false === $executable) { + throw new UnavailableLinterException('Cannot find PHP executable.'); + } + + if ('phpdbg' === \PHP_SAPI) { + if (!str_contains($executable, 'phpdbg')) { + throw new UnavailableLinterException('Automatically found PHP executable is non-standard phpdbg. Could not find proper PHP executable.'); + } + + // automatically found executable is `phpdbg`, let us try to fallback to regular `php` + $executable = str_replace('phpdbg', 'php', $executable); + + if (!is_executable($executable)) { + throw new UnavailableLinterException('Automatically found PHP executable is phpdbg. Could not find proper PHP executable.'); + } + } + } + + $this->processBuilder = new ProcessLinterProcessBuilder($executable); + $this->fileRemoval = new FileRemoval(); + } + + public function __destruct() + { + if (null !== $this->temporaryFile) { + $this->fileRemoval->delete($this->temporaryFile); + } + } + + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __serialize(): array + { + throw new \BadMethodCallException('Cannot serialize '.self::class); + } + + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @param array $data + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __unserialize(array $data): void + { + throw new \BadMethodCallException('Cannot unserialize '.self::class); + } + + public function isAsync(): bool + { + return true; + } + + public function lintFile(string $path): LintingResultInterface + { + return new ProcessLintingResult($this->createProcessForFile($path), $path); + } + + public function lintSource(string $source): LintingResultInterface + { + return new ProcessLintingResult($this->createProcessForSource($source), $this->temporaryFile); + } + + /** + * @param string $path path to file + */ + private function createProcessForFile(string $path): Process + { + // in case php://stdin + if (!is_file($path)) { + return $this->createProcessForSource(FileReader::createSingleton()->read($path)); + } + + $process = $this->processBuilder->build($path); + $process->setTimeout(10); + $process->start(); + + return $process; + } + + /** + * Create process that lint PHP code. + * + * @param string $source code + */ + private function createProcessForSource(string $source): Process + { + if (null === $this->temporaryFile) { + $this->temporaryFile = tempnam(sys_get_temp_dir(), 'cs_fixer_tmp_'); + $this->fileRemoval->observe($this->temporaryFile); + } + + if (false === @file_put_contents($this->temporaryFile, $source)) { + throw new IOException(\sprintf('Failed to write file "%s".', $this->temporaryFile), 0, null, $this->temporaryFile); + } + + return $this->createProcessForFile($this->temporaryFile); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php new file mode 100644 index 0000000..a054c9e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use Symfony\Component\Process\Process; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessLinterProcessBuilder +{ + private string $executable; + + /** + * @param string $executable PHP executable + */ + public function __construct(string $executable) + { + $this->executable = $executable; + } + + public function build(string $path): Process + { + return new Process([ + $this->executable, + '-l', + $path, + ]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php new file mode 100644 index 0000000..76981fe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use Symfony\Component\Process\Process; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessLintingResult implements LintingResultInterface +{ + private Process $process; + + private ?string $path; + + private ?bool $isSuccessful = null; + + public function __construct(Process $process, ?string $path = null) + { + $this->process = $process; + $this->path = $path; + } + + public function check(): void + { + if (!$this->isSuccessful()) { + // on some systems stderr is used, but on others, it's not + throw new LintingException($this->getProcessErrorMessage(), $this->process->getExitCode()); + } + } + + private function getProcessErrorMessage(): string + { + $errorOutput = $this->process->getErrorOutput(); + $output = strtok(ltrim('' !== $errorOutput ? $errorOutput : $this->process->getOutput()), "\n"); + + if (false === $output) { + return 'Fatal error: Unable to lint file.'; + } + + if (null !== $this->path) { + $needle = \sprintf('in %s ', $this->path); + $pos = strrpos($output, $needle); + + if (false !== $pos) { + $output = \sprintf('%s%s', substr($output, 0, $pos), substr($output, $pos + \strlen($needle))); + } + } + + $prefix = substr($output, 0, 18); + + if ('PHP Parse error: ' === $prefix) { + return \sprintf('Parse error: %s.', substr($output, 18)); + } + + if ('PHP Fatal error: ' === $prefix) { + return \sprintf('Fatal error: %s.', substr($output, 18)); + } + + return \sprintf('%s.', $output); + } + + private function isSuccessful(): bool + { + if (null === $this->isSuccessful) { + $this->process->wait(); + $this->isSuccessful = $this->process->isSuccessful(); + } + + return $this->isSuccessful; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php new file mode 100644 index 0000000..ac90efa --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\Hasher; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Handle PHP code linting. + * + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TokenizerLinter implements LinterInterface +{ + public function isAsync(): bool + { + return false; + } + + public function lintFile(string $path): LintingResultInterface + { + return $this->lintSource(FileReader::createSingleton()->read($path)); + } + + public function lintSource(string $source): LintingResultInterface + { + try { + // To lint, we will parse the source into Tokens. + // During that process, it might throw a ParseError or CompileError. + // If it won't, cache of tokenized version of source will be kept, which is great for Runner. + // Yet, first we need to clear already existing cache to not hit it and lint the code indeed. + $codeHash = Hasher::calculate($source); + Tokens::clearCache($codeHash); + Tokens::fromCode($source); + + return new TokenizerLintingResult(); + } catch (\CompileError|\ParseError $e) { + return new TokenizerLintingResult($e); + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php new file mode 100644 index 0000000..aef6e82 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TokenizerLintingResult implements LintingResultInterface +{ + private ?\Error $error; + + public function __construct(?\Error $error = null) + { + $this->error = $error; + } + + public function check(): void + { + if (null !== $this->error) { + throw new LintingException( + \sprintf('%s: %s on line %d.', $this->getMessagePrefix(), $this->error->getMessage(), $this->error->getLine()), + $this->error->getCode(), + $this->error, + ); + } + } + + private function getMessagePrefix(): string + { + return $this->error instanceof \ParseError ? 'Parse error' : 'Fatal error'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php new file mode 100644 index 0000000..d50b10b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Linter; + +/** + * Exception that is thrown when the chosen linter is not available on the environment. + * + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +class UnavailableLinterException extends \RuntimeException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ParallelAwareConfigInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ParallelAwareConfigInterface.php new file mode 100644 index 0000000..cff9bf3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ParallelAwareConfigInterface.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Runner\Parallel\ParallelConfig; + +/** + * @author Greg Korba + * + * @TODO 4.0 Include parallel runner config in main ConfigInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ParallelAwareConfigInterface extends ConfigInterface +{ + public function getParallelConfig(): ParallelConfig; + + /** + * @return $this + */ + public function setParallelConfig(ParallelConfig $config): ConfigInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php new file mode 100644 index 0000000..cf0eb34 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PharChecker implements PharCheckerInterface +{ + public function checkFileValidity(string $filename): ?string + { + try { + $phar = new \Phar($filename); + // free the variable to unlock the file + unset($phar); + } catch (\Exception $e) { + if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { + throw $e; + } + + return 'Failed to create Phar instance. '.$e->getMessage(); + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php new file mode 100644 index 0000000..6622822 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface PharCheckerInterface +{ + /** + * @return null|string the invalidity reason if any, null otherwise + */ + public function checkFileValidity(string $filename): ?string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Preg.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Preg.php new file mode 100644 index 0000000..e5e6b9e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Preg.php @@ -0,0 +1,220 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * This class replaces preg_* functions to better handling UTF8 strings, + * ensuring no matter "u" modifier is present or absent subject will be handled correctly. + * + * @author Kuba Werłos + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Preg +{ + /** + * @param array $matches + * @param int-mask $flags + * + * @param-out ($flags is PREG_OFFSET_CAPTURE + * ? array + * : ($flags is PREG_UNMATCHED_AS_NULL + * ? array + * : ($flags is int-mask&768 + * ? array + * : array + * ) + * ) + * ) $matches + * + * @throws PregException + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): bool + { + $result = @preg_match(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return 1 === $result; + } + + $result = @preg_match(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return 1 === $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, $pattern); + } + + /** + * @param array $matches + * @param int-mask $flags + * + * @param-out ($flags is PREG_PATTERN_ORDER + * ? array> + * : ($flags is PREG_SET_ORDER + * ? list> + * : ($flags is int-mask&(256|257) + * ? array> + * : ($flags is int-mask&258 + * ? list> + * : ($flags is int-mask&(512|513) + * ? array> + * : ($flags is int-mask&514 + * ? list> + * : ($flags is int-mask&770 + * ? list> + * : ($flags is 0 ? array> : array) + * ) + * ) + * ) + * ) + * ) + * ) + * ) $matches + * + * @return 0|positive-int + * + * @throws PregException + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = \PREG_PATTERN_ORDER, int $offset = 0): int + { + $result = @preg_match_all(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_match_all(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, $pattern); + } + + /** + * @param-out int $count + * + * @return ($subject is non-empty-string ? ($replacement is non-empty-string ? non-empty-string : string) : string) + * + * @throws PregException + */ + public static function replace(string $pattern, string $replacement, string $subject, int $limit = -1, ?int &$count = null): string + { + $result = @preg_replace(self::addUtf8Modifier($pattern), $replacement, $subject, $limit, $count); + if (null !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_replace(self::removeUtf8Modifier($pattern), $replacement, $subject, $limit, $count); + if (null !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, $pattern); + } + + /** + * @param-out int $count + * + * @throws PregException + */ + public static function replaceCallback(string $pattern, callable $callback, string $subject, int $limit = -1, ?int &$count = null): string + { + $result = @preg_replace_callback(self::addUtf8Modifier($pattern), $callback, $subject, $limit, $count); + if (null !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_replace_callback(self::removeUtf8Modifier($pattern), $callback, $subject, $limit, $count); + if (null !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, $pattern); + } + + /** + * @return ($flags is PREG_SPLIT_OFFSET_CAPTURE ? list}> : list) + * + * @throws PregException + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array + { + $result = @preg_split(self::addUtf8Modifier($pattern), $subject, $limit, $flags); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + $result = @preg_split(self::removeUtf8Modifier($pattern), $subject, $limit, $flags); + if (false !== $result && \PREG_NO_ERROR === preg_last_error()) { + return $result; + } + + throw self::newPregException(preg_last_error(), preg_last_error_msg(), __METHOD__, $pattern); + } + + private static function addUtf8Modifier(string $pattern): string + { + return $pattern.'u'; + } + + private static function removeUtf8Modifier(string $pattern): string + { + if ('' === $pattern) { + return ''; + } + + $delimiter = $pattern[0]; + + $endDelimiterPosition = strrpos($pattern, $delimiter); + \assert(\is_int($endDelimiterPosition)); + + return substr($pattern, 0, $endDelimiterPosition).str_replace('u', '', substr($pattern, $endDelimiterPosition)); + } + + /** + * Create the generic PregException message and tell more about such kind of error in the message. + */ + private static function newPregException(int $error, string $errorMsg, string $method, string $pattern): PregException + { + $result = null; + $errorMessage = null; + + try { + $result = ExecutorWithoutErrorHandler::execute(static fn () => preg_match($pattern, '')); + } catch (ExecutorWithoutErrorHandlerException $e) { + $result = false; + $errorMessage = $e->getMessage(); + } + + if (false !== $result) { + return new PregException(\sprintf('Unknown error occurred when calling %s: %s.', $method, $errorMsg), $error); + } + + $code = preg_last_error(); + + $message = \sprintf( + '(code: %d) %s', + $code, + preg_replace('~preg_[a-z_]+[()]{2}: ~', '', $errorMessage), + ); + + return new PregException( + \sprintf('%s(): Invalid PCRE pattern "%s": %s (version: %s)', $method, $pattern, $message, \PCRE_VERSION), + $code, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PregException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PregException.php new file mode 100644 index 0000000..d506fed --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/PregException.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * Exception that is thrown when PCRE function encounters an error. + * + * @author Kuba Werłos + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PregException extends \RuntimeException {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMajorMinorDeprecationSetDefinition.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMajorMinorDeprecationSetDefinition.php new file mode 100644 index 0000000..1fea5b6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMajorMinorDeprecationSetDefinition.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\Preg; + +/** + * @internal + * + * @TODO v4 remove me @MARKER_deprecated_migration_ruleset + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractMajorMinorDeprecationSetDefinition extends AbstractMigrationSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getRules(): array + { + $newName = Preg::replace('#(\d+)\.?(\d)#', '\1x\2', $this->getName()); + + return [ + $newName => true, + ]; + } + + public function getSuccessorsNames(): array + { + return array_keys($this->getRules()); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDefinition.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDefinition.php new file mode 100644 index 0000000..2fc4e29 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDefinition.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\Preg; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractMigrationSetDefinition extends AbstractRuleSetDefinition +{ + private string $entity; + + /** @var array{'major': int, 'minor': int} */ + private array $version; + + public function __construct() + { + parent::__construct(); + $this->parseRuleSetName(); + } + + /** + * @internal + */ + public function getEntity(): string + { + return $this->entity; + } + + public function getVersionMajorMinor(): string + { + return \sprintf('%s.%s', $this->version['major'], $this->version['minor']); + } + + public function getDescription(): string + { + $improvement = [ + 'PHPUnit' => 'tests code', + ][$this->getEntity()] ?? 'code'; + + return \sprintf('Rules to improve %s for %s %s compatibility.', $improvement, $this->getEntity(), $this->getVersionMajorMinor()); + } + + private function parseRuleSetName(): void + { + $name = $this->getName(); + + // @TODO v4 - `x?` -> `x` @MARKER_deprecated_migration_name_pattern + if (Preg::match('#^@PHPUnit(\d+)x?(\d)Migration.*$#', $name, $matches)) { + $this->entity = 'PHPUnit'; + $this->version = [ + 'major' => (int) $matches[1], + 'minor' => (int) $matches[2], + ]; + + return; + } + + // @TODO v4 - `x?` -> `x` @MARKER_deprecated_migration_name_pattern + if (Preg::match('#^@PHP(\d)x?(\d)Migration.*$#', $name, $matches)) { + $this->entity = 'PHP'; + $this->version = [ + 'major' => (int) $matches[1], + 'minor' => (int) $matches[2], + ]; + + return; + } + + throw new \RuntimeException(\sprintf('Cannot generate name of "%s" / "%s".', static::class, $name)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDefinition.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDefinition.php new file mode 100644 index 0000000..dc79176 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDefinition.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractRuleSetDefinition implements RuleSetDefinitionInterface +{ + public function __construct() {} + + public function getName(): string + { + $name = substr(static::class, 1 + (int) strrpos(static::class, '\\'), -3); + + return '@'.str_replace('Risky', ':risky', $name); + } + + public function isRisky(): bool + { + return str_contains(static::class, 'Risky'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticMigrationSetTrait.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticMigrationSetTrait.php new file mode 100644 index 0000000..53b4cbc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticMigrationSetTrait.php @@ -0,0 +1,114 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use Composer\Semver\Semver; +use PhpCsFixer\ComposerJsonReader; +use PhpCsFixer\ConfigurationException\UnresolvableAutoRuleSetConfigurationException; + +/** + * @internal + * + * @phpstan-require-implements AutomaticRuleSetDefinitionInterface + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +trait AutomaticMigrationSetTrait +{ + private function calculateTargetSet(string $setName, string $entity, bool $isRisky): string + { + static $set = null; + + if (null === $set) { + $actualVersion = self::calculateActualVersion($entity); + + $candidates = self::calculateCandidateSets($entity, $isRisky); + $composerCandidates = Semver::rsort(array_keys($candidates)); + + foreach ($composerCandidates as $candidate) { + if (Semver::satisfies($actualVersion, '>='.$candidate)) { + $set = $candidates[$candidate]; // @phpstan-ignore offsetAccess.notFound + + break; + } + } + + if (null === $set) { + throw new UnresolvableAutoRuleSetConfigurationException(\sprintf('No migration set found feasible for %s (%s %s).', $setName, $entity, $actualVersion)); + } + } + + return $set; + } + + /** + * @return list + */ + private static function getMigrationSets(): array + { + static $sets = null; + + if (null === $sets) { + $sets = array_values(array_filter( + RuleSets::getSetDefinitions(), + static fn (RuleSetDefinitionInterface $set): bool => !($set instanceof DeprecatedRuleSetDefinitionInterface) && is_subclass_of($set, AbstractMigrationSetDefinition::class), + )); + } + + return $sets; + } + + private static function calculateActualVersion(string $entity): string + { + $composerJsonReader = ComposerJsonReader::createSingleton(); + + if ('PHP' === $entity) { + $version = $composerJsonReader->getPhp(); + } elseif ('PHPUnit' === $entity) { + $version = $composerJsonReader->getPhpUnit(); + } else { + throw new \InvalidArgumentException(\sprintf('Entity "%s" is not supported.', $entity)); + } + + if (null === $version) { + throw new UnresolvableAutoRuleSetConfigurationException(\sprintf('Cannot detect %s version from "composer.json".', $entity)); + } + + return $version; + } + + /** + * @return array [ 'major.minor' => '@SetName', ... ] + */ + private static function calculateCandidateSets(string $entity, bool $isRisky): array + { + $candidates = []; + foreach (self::getMigrationSets() as $set) { + if ($set->getEntity() !== $entity) { + continue; + } + + if ($set->isRisky() !== $isRisky) { + continue; + } + + $candidates[$set->getVersionMajorMinor()] = $set->getName(); + } + + return $candidates; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticRuleSetDefinitionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticRuleSetDefinitionInterface.php new file mode 100644 index 0000000..d5fab1e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AutomaticRuleSetDefinitionInterface.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * Used to indicate that the ruleset can be automatically determined and will differ based on runtime conditions. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface AutomaticRuleSetDefinitionInterface +{ + public const WARNING_MESSAGE_DECORATED = 'This rule is automatic: it\'s definition depends on your project, eg "composer.json" file.'; + + /** + * @return array|bool> + */ + public function getRulesCandidates(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDefinitionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDefinitionInterface.php new file mode 100644 index 0000000..21f0e40 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDefinitionInterface.php @@ -0,0 +1,30 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface DeprecatedRuleSetDefinitionInterface extends RuleSetDefinitionInterface +{ + /** + * Returns names of rule sets to use instead, if any. + * + * @return list + */ + public function getSuccessorsNames(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDescriptionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDescriptionInterface.php new file mode 100644 index 0000000..90cfd2a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/DeprecatedRuleSetDescriptionInterface.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/* + * @deprecated + * @TODO v4 remove me @MARKER_deprecated_DeprecatedRuleSetDescriptionInterface + */ +class_alias( + DeprecatedRuleSetDefinitionInterface::class, + DeprecatedRuleSetDescriptionInterface::class, // @phpstan-ignore class.notFound +); diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/InternalRuleSetDefinitionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/InternalRuleSetDefinitionInterface.php new file mode 100644 index 0000000..6190252 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/InternalRuleSetDefinitionInterface.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface InternalRuleSetDefinitionInterface {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php new file mode 100644 index 0000000..6f1035d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php @@ -0,0 +1,162 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Future; +use PhpCsFixer\Utils; + +/** + * Set of rules to be used by fixer. + * + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RuleSet implements RuleSetInterface +{ + /** + * Group of rules generated from input set. + * + * The key is name of rule, value is configuration array or true. + * The key must not point to any set. + * + * @var array|true> + */ + private array $rules; + + public function __construct(array $set = []) + { + foreach ($set as $name => $value) { + if ('' === $name) { + throw new \InvalidArgumentException('Rule/set name must not be empty.'); + } + + if (\is_int($name)) { + throw new \InvalidArgumentException(\sprintf('Missing value for "%s" rule/set.', $value)); + } + + if (!\is_bool($value) && !\is_array($value)) { + $message = str_starts_with($name, '@') ? 'Set must be enabled (true) or disabled (false). Other values are not allowed.' : 'Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'; + + if (null === $value) { + $message .= ' To disable the '.(str_starts_with($name, '@') ? 'set' : 'rule').', use "FALSE" instead of "NULL".'; + } + + throw new InvalidFixerConfigurationException($name, $message); + } + } + + $this->rules = $this->resolveSet($set); + } + + public function hasRule(string $rule): bool + { + return \array_key_exists($rule, $this->rules); + } + + public function getRuleConfiguration(string $rule): ?array + { + if (!$this->hasRule($rule)) { + throw new \InvalidArgumentException(\sprintf('Rule "%s" is not in the set.', $rule)); + } + + if (true === $this->rules[$rule]) { + return null; + } + + return $this->rules[$rule]; + } + + public function getRules(): array + { + return $this->rules; + } + + /** + * Resolve input set into group of rules. + * + * @param array|bool> $rules + * + * @return array|true> + */ + private function resolveSet(array $rules): array + { + $resolvedRules = []; + + // expand sets + foreach ($rules as $name => $value) { + if (str_starts_with($name, '@')) { + if (!\is_bool($value)) { + throw new \UnexpectedValueException(\sprintf('Nested rule set "%s" configuration must be a boolean.', $name)); + } + + $set = $this->resolveSubset($name, $value); + $resolvedRules = array_merge($resolvedRules, $set); + } else { + $resolvedRules[$name] = $value; + } + } + + // filter out all resolvedRules that are off + $resolvedRules = array_filter( + $resolvedRules, + static fn ($value): bool => false !== $value, + ); + + return $resolvedRules; + } + + /** + * Resolve set rules as part of another set. + * + * If set value is false then disable all fixers in set, + * if not then get value from set item. + * + * @return array|bool> + */ + private function resolveSubset(string $setName, bool $setValue): array + { + $ruleSet = RuleSets::getSetDefinition($setName); + + if ($ruleSet instanceof DeprecatedRuleSetDefinitionInterface) { + $messageEnd = [] === $ruleSet->getSuccessorsNames() + ? 'No replacement available' + : \sprintf('Use %s instead', Utils::naturalLanguageJoin($ruleSet->getSuccessorsNames())); + + Future::triggerDeprecation(new \RuntimeException("Rule set \"{$setName}\" is deprecated. {$messageEnd}.")); + } + + $rules = $ruleSet->getRules(); + + foreach ($rules as $name => $value) { + if (str_starts_with($name, '@')) { + $set = $this->resolveSubset($name, $setValue); + unset($rules[$name]); + $rules = array_merge($rules, $set); + } elseif (!$setValue) { + $rules[$name] = false; + } else { + $rules[$name] = $value; + } + } + + return $rules; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDefinitionInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDefinitionInterface.php new file mode 100644 index 0000000..d31e9d6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDefinitionInterface.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface RuleSetDefinitionInterface +{ + public function getDescription(): string; + + public function getName(): string; + + /** + * Get all rules from rules set. + * + * @return array|bool> + */ + public function getRules(): array; + + public function isRisky(): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php new file mode 100644 index 0000000..7eb1395 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +/** + * Set of rules to be used by fixer. + * + * Example of set: ["@PSR2" => true, "@PSR1" => false, "strict" => true]. + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface RuleSetInterface +{ + /** + * @param array|bool> $set + */ + public function __construct(array $set = []); + + /** + * Get configuration for given rule. + * + * @return null|array + */ + public function getRuleConfiguration(string $rule): ?array; + + /** + * Get all rules from rules set. + * + * @return array|true> + */ + public function getRules(): array; + + /** + * Check given rule is in rules set. + */ + public function hasRule(string $rule): bool; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php new file mode 100644 index 0000000..adf441e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\RuleSetNameValidator; +use Symfony\Component\Finder\Finder; + +/** + * Set of rule sets to be used by fixer. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RuleSets +{ + /** + * @var null|array + */ + private static ?array $builtInSetDefinitions = null; + + /** + * @var array + */ + private static array $customRuleSetDefinitions = []; + + /** + * @return array + */ + public static function getSetDefinitions(): array + { + $allRuleSets = array_merge( + self::getBuiltInSetDefinitions(), + self::$customRuleSetDefinitions, + ); + + uksort($allRuleSets, static fn (string $x, string $y): int => strnatcasecmp($x, $y)); + + return $allRuleSets; + } + + /** + * @return array + */ + public static function getBuiltInSetDefinitions(): array + { + if (null === self::$builtInSetDefinitions) { + self::$builtInSetDefinitions = []; + + $finder = Finder::create() + ->files() + ->in(__DIR__.'/Sets') + ->exclude('Internal/') + ; + + foreach ($finder as $file) { + /** @var class-string $class */ + $class = 'PhpCsFixer\RuleSet\Sets\\'.$file->getBasename('.php'); + + /** @var RuleSetDefinitionInterface */ + $set = new $class(); + + if (!RuleSetNameValidator::isValid($set->getName(), false)) { + throw new \InvalidArgumentException(\sprintf('Rule set name invalid: %s', $set->getName())); + } + + self::$builtInSetDefinitions[$set->getName()] = $set; + } + + uksort(self::$builtInSetDefinitions, static fn (string $x, string $y): int => strnatcasecmp($x, $y)); + } + + return self::$builtInSetDefinitions; + } + + /** + * @return list + */ + public static function getSetDefinitionNames(): array + { + return array_keys(self::getSetDefinitions()); + } + + public static function getSetDefinition(string $name): RuleSetDefinitionInterface + { + $definitions = self::getSetDefinitions(); + + if (!isset($definitions[$name])) { + throw new \InvalidArgumentException(\sprintf('Set "%s" does not exist.', $name)); + } + + return $definitions[$name]; + } + + public static function registerCustomRuleSet(RuleSetDefinitionInterface $ruleset): void + { + $name = $ruleset->getName(); + + if (!RuleSetNameValidator::isValid($name, true)) { + throw new \InvalidArgumentException('RuleSet name must begin with "@" and a letter (a-z, A-Z), and can contain only letters (a-z, A-Z), numbers, underscores, slashes, colons, dots and hyphens.'); + } + + if (\array_key_exists($name, self::getSetDefinitions())) { + throw new \InvalidArgumentException(\sprintf('Set "%s" is already defined.', $name)); + } + + self::$customRuleSetDefinitions[$name] = $ruleset; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationRiskySet.php new file mode 100644 index 0000000..85a0133 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationRiskySet.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\AutomaticMigrationSetTrait; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AutoPHPMigrationRiskySet extends AbstractRuleSetDefinition implements AutomaticRuleSetDefinitionInterface +{ + use AutomaticMigrationSetTrait; + + public function getName(): string + { + return '@'.lcfirst(ltrim(parent::getName(), '@')); + } + + public function getRules(): array + { + return [ + $this->calculateTargetSet($this->getName(), 'PHP', $this->isRisky()) => true, + ]; + } + + public function getDescription(): string + { + return 'Migration rules to improve code towards the minimum ``PHP`` supported by your project (taken from ``composer.json`` file).'; + } + + public function getRulesCandidates(): array + { + $sets = array_values(self::calculateCandidateSets('PHP', $this->isRisky())); + ksort($sets); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationSet.php new file mode 100644 index 0000000..85d1d32 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPMigrationSet.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\AutomaticMigrationSetTrait; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AutoPHPMigrationSet extends AbstractRuleSetDefinition implements AutomaticRuleSetDefinitionInterface +{ + use AutomaticMigrationSetTrait; + + public function getName(): string + { + return '@'.lcfirst(ltrim(parent::getName(), '@')); + } + + public function getRules(): array + { + return [ + $this->calculateTargetSet($this->getName(), 'PHP', $this->isRisky()) => true, + ]; + } + + public function getDescription(): string + { + return 'Migration rules to improve code towards the minimum ``PHP`` supported by your project (taken from ``composer.json`` file).'; + } + + public function getRulesCandidates(): array + { + $sets = array_values(self::calculateCandidateSets('PHP', $this->isRisky())); + + ksort($sets); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPUnitMigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPUnitMigrationRiskySet.php new file mode 100644 index 0000000..7e1c8d8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoPHPUnitMigrationRiskySet.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\AutomaticMigrationSetTrait; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AutoPHPUnitMigrationRiskySet extends AbstractRuleSetDefinition implements AutomaticRuleSetDefinitionInterface +{ + use AutomaticMigrationSetTrait; + + public function getName(): string + { + return '@'.lcfirst(ltrim(parent::getName(), '@')); + } + + public function getRules(): array + { + return [ + $this->calculateTargetSet($this->getName(), 'PHPUnit', $this->isRisky()) => true, + ]; + } + + public function getDescription(): string + { + return 'Migration rules to improve test code towards the minimum ``PHPUnit`` supported by your project (taken from ``composer.json`` file).'; + } + + public function getRulesCandidates(): array + { + $sets = array_values(self::calculateCandidateSets('PHPUnit', $this->isRisky())); + + ksort($sets); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoRiskySet.php new file mode 100644 index 0000000..1c5ff33 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoRiskySet.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\ConfigurationException\UnresolvableAutoRuleSetConfigurationException; +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AutoRiskySet extends AbstractRuleSetDefinition implements AutomaticRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@'.lcfirst(ltrim(parent::getName(), '@')); + } + + public function getRules(): array + { + $sets = array_filter( + $this->getCandidates(), + fn (RuleSetDefinitionInterface $set): bool => $this->isSetDiscoverable($set), + ); + $sets = array_map( + static fn (RuleSetDefinitionInterface $set): string => $set->getName(), + $sets, + ); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } + + public function getDescription(): string + { + return 'Default (risky) rule set. Applies newest ``PER-CS`` and optimizations for ``PHP`` and ``PHPUnit``, based on project\'s ``composer.json`` file.'; + } + + public function getRulesCandidates(): array + { + $sets = array_map( + static fn (RuleSetDefinitionInterface $set): string => $set->getName(), + $this->getCandidates(), + ); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } + + /** @return list */ + private function getCandidates(): array + { + // order matters + return [ + new PERCSRiskySet(), + new AutoPHPMigrationRiskySet(), + new AutoPHPUnitMigrationRiskySet(), + ]; + } + + private function isSetDiscoverable(RuleSetDefinitionInterface $set): bool + { + try { + $set->getRules(); + + return true; + } catch (UnresolvableAutoRuleSetConfigurationException $unused) { + return false; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoSet.php new file mode 100644 index 0000000..7baf9fe --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/AutoSet.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\ConfigurationException\UnresolvableAutoRuleSetConfigurationException; +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @TODO refactor for DRY between Auto*Set classes // keradus + */ +final class AutoSet extends AbstractRuleSetDefinition implements AutomaticRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@'.lcfirst(ltrim(parent::getName(), '@')); + } + + public function getRules(): array + { + $sets = array_filter( + $this->getCandidates(), + fn (RuleSetDefinitionInterface $set): bool => $this->isSetDiscoverable($set), + ); + $sets = array_map( + static fn (RuleSetDefinitionInterface $set): string => $set->getName(), + $sets, + ); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } + + public function getDescription(): string + { + return 'Default rule set. Applies newest ``PER-CS`` and optimizations for ``PHP``, based on project\'s ``composer.json`` file.'; + } + + public function getRulesCandidates(): array + { + $sets = array_map( + static fn (RuleSetDefinitionInterface $set): string => $set->getName(), + $this->getCandidates(), + ); + + return array_combine($sets, array_fill(0, \count($sets), true)); + } + + /** @return list */ + private function getCandidates(): array + { + // order matters + return [ + new PERCSSet(), + new AutoPHPMigrationSet(), + ]; + } + + private function isSetDiscoverable(RuleSetDefinitionInterface $set): bool + { + try { + $set->getRules(); + + return true; + } catch (UnresolvableAutoRuleSetConfigurationException $unused) { + return false; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php new file mode 100644 index 0000000..fcb2b9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DoctrineAnnotationSet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + 'doctrine_annotation_array_assignment' => [ + 'operator' => ':', + ], + 'doctrine_annotation_braces' => true, + 'doctrine_annotation_indentation' => true, + 'doctrine_annotation_spaces' => [ + 'before_array_assignments_colon' => false, + ], + ]; + } + + public function getDescription(): string + { + return 'Rules covering ``Doctrine`` annotations with configuration based on examples found in `Doctrine Annotation documentation `_ and `Symfony documentation `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10RiskySet.php new file mode 100644 index 0000000..70e8eb5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10RiskySet.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS10RiskySet extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS1.0:risky'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS1x0RiskySet(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10Set.php new file mode 100644 index 0000000..eef15fd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS10Set.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS10Set extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS1.0'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS1x0Set(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php new file mode 100644 index 0000000..e633f6a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS1x0RiskySet extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS1x0:risky'; + } + + public function getRules(): array + { + return [ + '@PSR12:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 1.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php new file mode 100644 index 0000000..2fa3023 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS1x0Set extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS1x0'; + } + + public function getRules(): array + { + return [ + '@PSR12' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 1.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20RiskySet.php new file mode 100644 index 0000000..8c8987f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20RiskySet.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS20RiskySet extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS2.0:risky'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS2x0RiskySet(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20Set.php new file mode 100644 index 0000000..a29da12 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS20Set.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS20Set extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS2.0'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS2x0Set(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php new file mode 100644 index 0000000..9748df2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0RiskySet.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS2x0RiskySet extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS2x0:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS1x0:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 2.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php new file mode 100644 index 0000000..3032711 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS2x0Set.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v2.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/2.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS2x0Set extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS2x0'; + } + + public function getRules(): array + { + return [ + '@PER-CS1x0' => true, + 'array_indentation' => true, + 'array_syntax' => true, + 'attribute_block_no_spaces' => true, + 'cast_spaces' => true, + 'concat_space' => ['spacing' => 'one'], + 'function_declaration' => [ + 'closure_fn_spacing' => 'none', + ], + 'method_argument_space' => [ + 'after_heredoc' => false, // @TODO: default value of this option changed, consider to switch to new default + ], + 'new_with_parentheses' => [ + 'anonymous_class' => false, + ], + 'single_line_empty_body' => true, + 'single_space_around_construct' => [ + 'constructs_followed_by_a_single_space' => [ + 'abstract', + 'as', + 'case', + 'catch', + 'class', + 'const', + 'const_import', + 'do', + 'else', + 'elseif', + 'enum', + 'final', + 'finally', + 'for', + 'foreach', + 'function', + 'function_import', + 'if', + 'insteadof', + 'interface', + 'match', + 'named_argument', + 'namespace', + 'new', + 'private', + 'protected', + 'public', + 'readonly', + 'static', + 'switch', + 'trait', + 'try', + 'type_colon', + 'use', + 'use_lambda', + 'while', + ], + 'constructs_preceded_by_a_single_space' => [ + 'as', + 'else', + 'elseif', + 'use_lambda', + ], + ], + 'trailing_comma_in_multiline' => [ + 'after_heredoc' => true, + 'elements' => [ + 'arguments', + 'array_destructuring', + 'arrays', + 'match', + 'parameters', + ], + ], + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 2.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30RiskySet.php new file mode 100644 index 0000000..eac8f01 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30RiskySet.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v3.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/3.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS30RiskySet extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS3.0:risky'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS3x0RiskySet(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30Set.php new file mode 100644 index 0000000..798d1a6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS30Set.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; + +/** + * @internal + * + * PER Coding Style v3.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/3.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS30Set extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER-CS3.0'; + } + + public function getRules(): array + { + return $this->getProxiedSet()->getRules(); + } + + public function getDescription(): string + { + return $this->getProxiedSet()->getDescription(); + } + + public function getSuccessorsNames(): array + { + return [$this->getProxiedSet()->getName()]; + } + + private function getProxiedSet(): RuleSetDefinitionInterface + { + return new PERCS3x0Set(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0RiskySet.php new file mode 100644 index 0000000..10a5d30 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0RiskySet.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v3.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/3.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS3x0RiskySet extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS3x0:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS2x0:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 3.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0Set.php new file mode 100644 index 0000000..556aac6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS3x0Set.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * PER Coding Style v3.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/3.0.0/spec.md + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCS3x0Set extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS3x0'; + } + + public function getRules(): array + { + return [ + '@PER-CS2x0' => true, + 'nullable_type_declaration' => true, + 'operator_linebreak' => true, + 'ordered_types' => [ + 'null_adjustment' => 'always_last', + 'sort_algorithm' => 'none', + ], + 'single_class_element_per_statement' => true, + 'types_spaces' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style 3.0 `_.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php new file mode 100644 index 0000000..24b493b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSRiskySet.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSets; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCSRiskySet extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS:risky'; + } + + public function getRules(): array + { + return [ + $this->getHighestPerCsSet()->getName() => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style `_, Set is an alias for the latest revision of ``PER-CS`` rules - use it if you always want to be in sync with newest ``PER-CS`` standard.'; + } + + private function getHighestPerCsSet(): RuleSetDefinitionInterface + { + static $set = null; + + if (null === $set) { + $currentSet = $this; + + $sets = array_filter( + RuleSets::getSetDefinitions(), + static fn (RuleSetDefinitionInterface $set): bool => !($set instanceof DeprecatedRuleSetDefinitionInterface) + && $set->isRisky() === $currentSet->isRisky() + && $set->getName() !== $currentSet->getName() + && str_starts_with($set->getName(), str_replace(':risky', '', $currentSet->getName())), + ); + + ksort($sets, \SORT_NATURAL); + + $set = array_pop($sets); + } + + return $set; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php new file mode 100644 index 0000000..bc1b893 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCSSet.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; +use PhpCsFixer\RuleSet\RuleSets; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERCSSet extends AbstractRuleSetDefinition +{ + public function getName(): string + { + return '@PER-CS'; + } + + public function getRules(): array + { + return [ + $this->getHighestPerCsSet()->getName() => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PER Coding Style `_, Set is an alias for the latest revision of ``PER-CS`` rules - use it if you always want to be in sync with newest ``PER-CS`` standard.'; + } + + private function getHighestPerCsSet(): RuleSetDefinitionInterface + { + static $set = null; + + if (null === $set) { + $currentSet = $this; + + $sets = array_filter( + RuleSets::getSetDefinitions(), + static fn (RuleSetDefinitionInterface $set): bool => !($set instanceof DeprecatedRuleSetDefinitionInterface) + && $set->isRisky() === $currentSet->isRisky() + && $set->getName() !== $currentSet->getName() + && str_starts_with($set->getName(), $currentSet->getName()), + ); + + ksort($sets, \SORT_NATURAL); + + $set = array_pop($sets); + } + + return $set; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php new file mode 100644 index 0000000..5c0f436 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; + +/** + * @internal + * + * @deprecated use `@PER-CS:risky` instead + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style v2.0. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERRiskySet extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getName(): string + { + return '@PER:risky'; + } + + public function getRules(): array + { + return [ + '@PER-CS:risky' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the newest ``PER-CS`` risky rules. It is recommended you use ``@PER-CS2.0:risky`` instead if you want to stick with stable ruleset.'; + } + + public function getSuccessorsNames(): array + { + return ['@PER-CS:risky']; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php new file mode 100644 index 0000000..dfb2e6e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; +use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; + +/** + * @internal + * + * @deprecated use `@PER-CS` instead + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style v2.0. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PERSet extends AbstractRuleSetDefinition implements DeprecatedRuleSetDefinitionInterface +{ + public function getRules(): array + { + return [ + '@PER-CS' => true, + ]; + } + + public function getDescription(): string + { + return 'Alias for the newest ``PER-CS`` rules. It is recommended you use ``@PER-CS3.0`` instead if you want to stick with stable ruleset.'; + } + + public function getSuccessorsNames(): array + { + return ['@PER-CS']; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php new file mode 100644 index 0000000..8002068 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP54MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php new file mode 100644 index 0000000..b139c83 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP56MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x4MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x4MigrationSet.php new file mode 100644 index 0000000..10ad710 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x4MigrationSet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP5x4MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + 'array_syntax' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x6MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x6MigrationRiskySet.php new file mode 100644 index 0000000..d1bd793 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP5x6MigrationRiskySet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP5x6MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + 'pow_to_exponentiation' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php new file mode 100644 index 0000000..f63090c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP70MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php new file mode 100644 index 0000000..e56ce78 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP70MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php new file mode 100644 index 0000000..abdf48d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP71MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php new file mode 100644 index 0000000..d751d8d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP71MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php new file mode 100644 index 0000000..f86e09d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP73MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php new file mode 100644 index 0000000..e2a0dbc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP74MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php new file mode 100644 index 0000000..4bb2a5e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP74MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationRiskySet.php new file mode 100644 index 0000000..da886d7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationRiskySet.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP5x6Migration:risky' => true, + 'combine_nested_dirname' => true, + 'declare_strict_types' => true, + 'non_printable_character' => true, + 'random_api_migration' => [ // @TODO v4 replace with `true` + 'replacements' => [ + 'mt_getrandmax' => 'getrandmax', + 'mt_rand' => 'random_int', + 'mt_srand' => 'srand', + 'rand' => 'random_int', + ], + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationSet.php new file mode 100644 index 0000000..4db2651 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x0MigrationSet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x0MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP5x4Migration' => true, + 'ternary_to_null_coalescing' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationRiskySet.php new file mode 100644 index 0000000..c5ba6df --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x1MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x0Migration:risky' => true, + 'void_return' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationSet.php new file mode 100644 index 0000000..852e9ed --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x1MigrationSet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x1MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x0Migration' => true, + 'list_syntax' => true, + 'modifier_keywords' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x3MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x3MigrationSet.php new file mode 100644 index 0000000..adf8768 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x3MigrationSet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x3MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x1Migration' => true, + 'heredoc_indentation' => true, + 'method_argument_space' => ['after_heredoc' => true], + 'no_whitespace_before_comma_in_array' => ['after_heredoc' => true], + 'trailing_comma_in_multiline' => ['after_heredoc' => true], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationRiskySet.php new file mode 100644 index 0000000..bb47342 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationRiskySet.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x4MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x1Migration:risky' => true, + 'implode_call' => true, + 'no_alias_functions' => true, + 'use_arrow_functions' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationSet.php new file mode 100644 index 0000000..f18460c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP7x4MigrationSet.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP7x4MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x3Migration' => true, + 'assign_null_coalescing_to_coalesce_equal' => true, + 'normalize_index_brace' => true, + 'short_scalar_cast' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php new file mode 100644 index 0000000..51c4928 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP80MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php new file mode 100644 index 0000000..02349fc --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP80MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php new file mode 100644 index 0000000..fdf9051 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP81MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationRiskySet.php new file mode 100644 index 0000000..5e51547 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP82MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php new file mode 100644 index 0000000..59c8f11 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP82MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php new file mode 100644 index 0000000..17d4014 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP83MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP83MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP84MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP84MigrationSet.php new file mode 100644 index 0000000..0735a44 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP84MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP84MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP85MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP85MigrationSet.php new file mode 100644 index 0000000..7e46b91 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP85MigrationSet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP85MigrationSet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationRiskySet.php new file mode 100644 index 0000000..8b39b0a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationRiskySet.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x4Migration:risky' => true, + 'get_class_to_class_keyword' => true, + 'modernize_strpos' => true, + 'no_alias_functions' => [ + 'sets' => [ + '@all', + ], + ], + 'no_php4_constructor' => true, + 'no_unneeded_final_method' => true, // final private method (not constructor) are no longer allowed >= PHP8.0 + 'no_unreachable_default_argument_value' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationSet.php new file mode 100644 index 0000000..c9b3442 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x0MigrationSet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x0MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP7x4Migration' => true, + 'clean_namespace' => true, + 'no_unset_cast' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationRiskySet.php new file mode 100644 index 0000000..dffb766 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationRiskySet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x1MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x0Migration:risky' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationSet.php new file mode 100644 index 0000000..8e8fc38 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x1MigrationSet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x1MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x0Migration' => true, + 'octal_notation' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationRiskySet.php new file mode 100644 index 0000000..1ee4418 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x2MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x1Migration:risky' => true, + 'phpdoc_readonly_class_comment_to_keyword' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationSet.php new file mode 100644 index 0000000..5335c82 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x2MigrationSet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x2MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x1Migration' => true, + 'simple_to_complex_string_variable' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationRiskySet.php new file mode 100644 index 0000000..adf2569 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationRiskySet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x3MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x2Migration:risky' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationSet.php new file mode 100644 index 0000000..56cf6db --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x3MigrationSet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x3MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x2Migration' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationRiskySet.php new file mode 100644 index 0000000..3662297 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationRiskySet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x4MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x3Migration:risky' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationSet.php new file mode 100644 index 0000000..920ac96 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x4MigrationSet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x4MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x3Migration' => true, + 'new_expression_parentheses' => true, + 'nullable_type_declaration_for_default_null_value' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationRiskySet.php new file mode 100644 index 0000000..9f77a2e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x5MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x4Migration:risky' => true, + 'modern_serialization_methods' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationSet.php new file mode 100644 index 0000000..cecd27f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP8x5MigrationSet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHP8x5MigrationSet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP8x4Migration' => true, + 'switch_case_semicolon_to_colon' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php new file mode 100644 index 0000000..9bf5f10 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit100MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit10x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit10x0MigrationRiskySet.php new file mode 100644 index 0000000..240c0b6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit10x0MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit10x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit9x1Migration:risky' => true, + 'php_unit_data_provider_static' => ['force' => true], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit11x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit11x0MigrationRiskySet.php new file mode 100644 index 0000000..ab7a4ba --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit11x0MigrationRiskySet.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit11x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit10x0Migration:risky' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php new file mode 100644 index 0000000..bbe5450 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit30MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php new file mode 100644 index 0000000..26f2302 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit32MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php new file mode 100644 index 0000000..20173b2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit35MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x0MigrationRiskySet.php new file mode 100644 index 0000000..8e3a996 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x0MigrationRiskySet.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit3x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_0, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x2MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x2MigrationRiskySet.php new file mode 100644 index 0000000..e9bf90a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x2MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit3x2MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit3x0Migration:risky' => true, + 'php_unit_no_expectation_annotation' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_2, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x5MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x5MigrationRiskySet.php new file mode 100644 index 0000000..94f7090 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit3x5MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit3x5MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit3x2Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_3_5, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php new file mode 100644 index 0000000..541f060 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit43MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php new file mode 100644 index 0000000..1d69611 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit48MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x3MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x3MigrationRiskySet.php new file mode 100644 index 0000000..f83cc4c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x3MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit4x3MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit3x5Migration:risky' => true, + 'php_unit_no_expectation_annotation' => [ + 'target' => PhpUnitTargetVersion::VERSION_4_3, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x8MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x8MigrationRiskySet.php new file mode 100644 index 0000000..355d822 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit4x8MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit4x8MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit4x3Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_4_8, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php new file mode 100644 index 0000000..fd931b8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit50MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php new file mode 100644 index 0000000..b5eafb9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit52MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php new file mode 100644 index 0000000..58892ba --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit54MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php new file mode 100644 index 0000000..c4aa26e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit55MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php new file mode 100644 index 0000000..388c3eb --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit56MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php new file mode 100644 index 0000000..8d14483 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit57MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x0MigrationRiskySet.php new file mode 100644 index 0000000..845d497 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x0MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit4x8Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_0, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x2MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x2MigrationRiskySet.php new file mode 100644 index 0000000..c8c75f8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x2MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x2MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x0Migration:risky' => true, + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_2, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x4MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x4MigrationRiskySet.php new file mode 100644 index 0000000..beb1c0d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x4MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x4MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x2Migration:risky' => true, + 'php_unit_mock' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_4, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x5MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x5MigrationRiskySet.php new file mode 100644 index 0000000..e6a7289 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x5MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x5MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x4Migration:risky' => true, + 'php_unit_mock' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_5, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x6MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x6MigrationRiskySet.php new file mode 100644 index 0000000..b6154b5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x6MigrationRiskySet.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x6MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x5Migration:risky' => true, + 'php_unit_dedicate_assert' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_6, + ], + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_6, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x7MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x7MigrationRiskySet.php new file mode 100644 index 0000000..d25d00f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit5x7MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit5x7MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x6Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_5_7, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php new file mode 100644 index 0000000..b25d2a0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit60MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit6x0MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit6x0MigrationRiskySet.php new file mode 100644 index 0000000..d5ea9c5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit6x0MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit6x0MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit5x7Migration:risky' => true, + 'php_unit_namespaced' => [ + 'target' => PhpUnitTargetVersion::VERSION_6_0, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php new file mode 100644 index 0000000..4ff82c7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit75MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit7x5MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit7x5MigrationRiskySet.php new file mode 100644 index 0000000..e648182 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit7x5MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit7x5MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit6x0Migration:risky' => true, + 'php_unit_dedicate_assert_internal_type' => [ + 'target' => PhpUnitTargetVersion::VERSION_7_5, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php new file mode 100644 index 0000000..0443154 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit84MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit8x4MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit8x4MigrationRiskySet.php new file mode 100644 index 0000000..e90bb5b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit8x4MigrationRiskySet.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit8x4MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit7x5Migration:risky' => true, + 'php_unit_expectation' => [ + 'target' => PhpUnitTargetVersion::VERSION_8_4, + ], + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit91MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit91MigrationRiskySet.php new file mode 100644 index 0000000..53013c2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit91MigrationRiskySet.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMajorMinorDeprecationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit91MigrationRiskySet extends AbstractMajorMinorDeprecationSetDefinition {} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit9x1MigrationRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit9x1MigrationRiskySet.php new file mode 100644 index 0000000..7ee55a1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit9x1MigrationRiskySet.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PHPUnit9x1MigrationRiskySet extends AbstractMigrationSetDefinition +{ + public function getRules(): array + { + return [ + '@PHPUnit8x4Migration:risky' => true, + 'php_unit_assert_new_names' => true, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php new file mode 100644 index 0000000..d8e4211 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PSR12RiskySet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + 'no_trailing_whitespace_in_string' => true, + 'no_unreachable_default_argument_value' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php new file mode 100644 index 0000000..151c396 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PSR12Set extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PSR2' => true, + 'binary_operator_spaces' => [ + 'default' => 'at_least_single_space', + ], + 'blank_line_after_opening_tag' => true, + 'blank_line_between_import_groups' => true, + 'blank_lines_before_namespace' => true, + 'braces_position' => [ + 'allow_single_line_anonymous_functions' => false, + 'allow_single_line_empty_anonymous_classes' => true, + ], + 'class_definition' => [ + 'inline_constructor_arguments' => false, // handled by method_argument_space fixer + 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes + ], + 'compact_nullable_type_declaration' => true, + 'declare_equal_normalize' => true, + 'lowercase_cast' => true, + 'lowercase_static_reference' => true, + 'modifier_keywords' => true, + 'new_with_parentheses' => [ + 'anonymous_class' => true, + ], + 'no_blank_lines_after_class_opening' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements + ], + ], + 'no_leading_import_slash' => true, + 'no_whitespace_in_blank_line' => true, + 'ordered_class_elements' => [ + 'order' => [ + 'use_trait', + ], + ], + 'ordered_imports' => [ + 'imports_order' => [ + 'class', + 'function', + 'const', + ], + 'sort_algorithm' => 'none', + ], + 'return_type_declaration' => true, + 'short_scalar_cast' => true, + 'single_import_per_statement' => ['group_to_single_imports' => false], + 'single_space_around_construct' => [ + 'constructs_followed_by_a_single_space' => [ + 'abstract', + 'as', + 'case', + 'catch', + 'class', + 'const_import', + 'do', + 'else', + 'elseif', + 'final', + 'finally', + 'for', + 'foreach', + 'function', + 'function_import', + 'if', + 'insteadof', + 'interface', + 'namespace', + 'new', + 'private', + 'protected', + 'public', + 'static', + 'switch', + 'trait', + 'try', + 'use', + 'use_lambda', + 'while', + ], + 'constructs_preceded_by_a_single_space' => [ + 'as', + 'else', + 'elseif', + 'use_lambda', + ], + ], + 'single_trait_insert_per_statement' => true, + 'ternary_operator_spaces' => true, + 'unary_operator_spaces' => [ + 'only_dec_inc' => true, + ], + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php new file mode 100644 index 0000000..d566528 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PSR1Set extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + 'encoding' => true, + 'full_opening_tag' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-1 `_ standard.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php new file mode 100644 index 0000000..4082a39 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PSR2Set extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PSR1' => true, + 'blank_line_after_namespace' => true, + 'braces_position' => [ + 'allow_single_line_anonymous_functions' => false, + ], + 'class_definition' => true, + 'constant_case' => true, + 'control_structure_braces' => true, + 'control_structure_continuation_position' => true, + 'elseif' => true, + 'function_declaration' => [ + 'closure_fn_spacing' => 'one', // @TODO: default value of this option changed, consider to switch to new default + ], + 'indentation_type' => true, + 'line_ending' => true, + 'lowercase_keywords' => true, + 'method_argument_space' => [ + 'after_heredoc' => false, // @TODO: default value of this option changed, consider to switch to new default + 'attribute_placement' => 'ignore', + 'on_multiline' => 'ensure_fully_multiline', + ], + 'modifier_keywords' => ['elements' => ['method', 'property']], + 'no_break_comment' => true, + 'no_closing_tag' => true, + 'no_multiple_statements_per_line' => true, + 'no_space_around_double_colon' => true, + 'no_spaces_after_function_name' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'single_blank_line_at_eof' => true, + 'single_class_element_per_statement' => [ + 'elements' => [ + 'property', + ], + ], + 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'single_space_around_construct' => [ + 'constructs_followed_by_a_single_space' => [ + 'abstract', + 'as', + 'case', + 'catch', + 'class', + 'do', + 'else', + 'elseif', + 'final', + 'for', + 'foreach', + 'function', + 'if', + 'interface', + 'namespace', + 'private', + 'protected', + 'public', + 'static', + 'switch', + 'trait', + 'try', + 'use_lambda', + 'while', + ], + 'constructs_preceded_by_a_single_space' => [ + 'as', + 'else', + 'elseif', + 'use_lambda', + ], + ], + 'spaces_inside_parentheses' => true, + 'statement_indentation' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow `PSR-2 `_ standard.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php new file mode 100644 index 0000000..bc795a3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpCsFixerRiskySet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PER-CS:risky' => true, + '@Symfony:risky' => true, + 'comment_to_phpdoc' => true, + 'declare_strict_types' => true, + 'final_internal_class' => true, + 'get_class_to_class_keyword' => false, + 'modernize_strpos' => false, + // @TODO: consider switching to `true`, like in @Symfony + 'native_constant_invocation' => [ + 'fix_built_in' => false, + 'include' => [ + 'DIRECTORY_SEPARATOR', + 'PHP_INT_SIZE', + 'PHP_SAPI', + 'PHP_VERSION_ID', + ], + 'scope' => 'namespaced', + 'strict' => true, + ], + 'no_alias_functions' => [ + 'sets' => [ + '@all', + ], + ], + 'no_trailing_whitespace_in_string' => true, // override Symfony to mimics PER / CS + 'no_unset_on_property' => true, + 'php_unit_data_provider_name' => true, + 'php_unit_data_provider_return_type' => true, + 'php_unit_data_provider_static' => ['force' => true], + 'php_unit_strict' => true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'strict_comparison' => true, + 'strict_param' => true, + 'void_return' => true, // override Symfony + 'yield_from_array_to_yields' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules recommended by ``PHP CS Fixer`` team, highly opinionated. Extends ``@PER-CS:risky`` and ``@Symfony:risky``.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php new file mode 100644 index 0000000..164df96 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpCsFixerSet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PER-CS' => true, + '@Symfony' => true, + 'blank_line_before_statement' => [ + 'statements' => [ + 'break', + 'case', + 'continue', + 'declare', + 'default', + 'exit', + 'goto', + 'include', + 'include_once', + 'phpdoc', + 'require', + 'require_once', + 'return', + 'switch', + 'throw', + 'try', + 'yield', + 'yield_from', + ], + ], + 'combine_consecutive_issets' => true, + 'combine_consecutive_unsets' => true, + 'empty_loop_body' => true, + 'explicit_indirect_variable' => true, + 'explicit_string_variable' => true, + 'fully_qualified_strict_types' => [ + 'import_symbols' => true, + ], + 'heredoc_to_nowdoc' => true, + 'method_argument_space' => [ + 'after_heredoc' => true, + 'on_multiline' => 'ensure_fully_multiline', + ], + 'method_chaining_indentation' => true, + 'multiline_comment_opening_closing' => true, + 'multiline_whitespace_before_semicolons' => [ + 'strategy' => 'new_line_for_chained_calls', + ], + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'attribute', + 'break', + 'case', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'switch', + 'throw', + 'use', + ], + ], + 'no_superfluous_elseif' => true, + 'no_superfluous_phpdoc_tags' => [ + 'allow_hidden_params' => true, + 'allow_mixed' => true, // @TODO revalidate to keep `true` or unify into `false` + 'remove_inheritdoc' => true, + ], + 'no_whitespace_in_empty_array' => true, + 'operator_linebreak' => true, + 'ordered_class_elements' => true, + 'ordered_types' => [ + 'null_adjustment' => 'always_last', + ], + 'php_unit_data_provider_method_order' => true, + 'php_unit_internal_class' => true, + 'php_unit_test_class_requires_covers' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_no_duplicate_types' => true, + 'phpdoc_no_empty_return' => true, + 'phpdoc_order_by_value' => true, + 'phpdoc_types_order' => true, + 'return_assignment' => true, + 'self_static_accessor' => true, + 'single_line_comment_style' => true, + 'single_line_empty_body' => true, + 'single_line_throw' => false, + 'string_implicit_backslashes' => true, + 'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['array_destructuring', 'arrays']], + 'whitespace_after_comma_in_array' => ['ensure_single_space' => true], + ]; + } + + public function getDescription(): string + { + return 'Rules recommended by ``PHP CS Fixer`` team, highly opinionated. Extends ``@PER-CS`` and ``@Symfony``.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php new file mode 100644 index 0000000..8a2b7b6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SymfonyRiskySet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PHP5x6Migration:risky' => true, + '@PSR12:risky' => true, + 'array_push' => true, + 'combine_nested_dirname' => true, + 'declare_strict_types' => [ + 'strategy' => 'remove', + ], + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'error_suppression' => true, + 'fopen_flag_order' => true, + 'fopen_flags' => [ + 'b_mode' => false, + ], + 'function_to_constant' => true, + 'get_class_to_class_keyword' => true, + 'implode_call' => true, + 'is_null' => true, + 'logical_operators' => true, + 'long_to_shorthand_operator' => true, + 'modern_serialization_methods' => true, + 'modernize_strpos' => true, + 'modernize_types_casting' => true, + 'native_constant_invocation' => ['strict' => false], + 'native_function_invocation' => [ + 'include' => [ + '@compiler_optimized', + ], + 'scope' => 'namespaced', + 'strict' => true, + ], + 'no_alias_functions' => true, + 'no_homoglyph_names' => true, + 'no_php4_constructor' => true, + 'no_trailing_whitespace_in_string' => false, // override PER-CS + 'no_unneeded_final_method' => true, + 'no_useless_sprintf' => true, + 'non_printable_character' => true, + 'ordered_traits' => true, + 'php_unit_construct' => true, + 'php_unit_mock_short_will_return' => true, + 'php_unit_set_up_tear_down_visibility' => true, + 'php_unit_test_annotation' => true, + 'psr_autoloading' => true, + 'self_accessor' => true, + 'set_type_to_cast' => true, + 'static_lambda' => true, + 'string_length_to_empty' => true, + 'string_line_ending' => true, + 'ternary_to_elvis_operator' => true, + 'void_return' => [ + 'fix_lambda' => false, + ], + ]; + } + + public function getDescription(): string + { + return 'Rules that follow the official `Symfony Coding Standards `_. Extends ``@PER-CS:risky``.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php new file mode 100644 index 0000000..131110c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php @@ -0,0 +1,269 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\Phpdoc\PhpdocSeparationFixer; +use PhpCsFixer\RuleSet\AbstractRuleSetDefinition; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SymfonySet extends AbstractRuleSetDefinition +{ + public function getRules(): array + { + return [ + '@PER-CS3x0' => true, + 'align_multiline_comment' => true, + 'backtick_to_shell_exec' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_statement' => [ + 'statements' => [ + 'return', + ], + ], + 'braces_position' => [ + 'allow_single_line_anonymous_functions' => true, + 'allow_single_line_empty_anonymous_classes' => true, + ], + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one', + ], + ], + 'class_definition' => [ + 'single_line' => true, + ], + 'class_reference_name_casing' => true, + 'clean_namespace' => true, + 'concat_space' => true, // overrides @PER-CS2.0 + 'declare_parentheses' => true, + 'echo_tag_syntax' => true, + 'empty_loop_body' => ['style' => 'braces'], + 'empty_loop_condition' => true, + 'fully_qualified_strict_types' => true, + 'function_declaration' => [ // overrides @PER-CS2.0 + 'closure_fn_spacing' => 'one', // @TODO: default value of this option changed, consider to switch to new default + ], + 'general_phpdoc_tag_rename' => [ + 'replacements' => [ + 'inheritDocs' => 'inheritDoc', + ], + ], + 'global_namespace_import' => [ + 'import_classes' => false, + 'import_constants' => false, + 'import_functions' => false, + ], + 'include' => true, + 'increment_style' => true, + 'integer_literal_case' => true, + 'lambda_not_used_import' => true, + 'linebreak_after_opening_tag' => true, + 'magic_constant_casing' => true, + 'magic_method_casing' => true, + 'method_argument_space' => [ // overrides @PER-CS2.0 + 'after_heredoc' => true, + 'on_multiline' => 'ignore', + ], + 'native_function_casing' => true, + 'native_type_declaration_casing' => true, + 'no_alias_language_construct_call' => true, + 'no_alternative_syntax' => true, + 'no_binary_string' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'attribute', + 'case', + 'continue', + 'curly_brace_block', + 'default', + 'extra', + 'parenthesis_brace_block', + 'square_brace_block', + 'switch', + 'throw', + 'use', + ], + ], + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_null_property_initialization' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_around_offset' => true, + 'no_superfluous_phpdoc_tags' => [ + 'allow_hidden_params' => true, + 'remove_inheritdoc' => true, + ], + 'no_trailing_comma_in_singleline' => true, + 'no_unneeded_braces' => [ + 'namespaces' => true, + ], + 'no_unneeded_control_parentheses' => [ + 'statements' => [ + 'break', + 'clone', + 'continue', + 'echo_print', + 'negative_instanceof', + 'others', + 'return', + 'switch_case', + 'yield', + 'yield_from', + ], + ], + 'no_unneeded_import_alias' => true, + 'no_unset_cast' => true, + 'no_unused_imports' => true, + 'no_useless_concat_operator' => true, + 'no_useless_else' => true, + 'no_useless_nullsafe_operator' => true, + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => ['after_heredoc' => true], + 'normalize_index_brace' => true, + 'nullable_type_declaration_for_default_null_value' => true, + 'object_operator_without_whitespace' => true, + 'operator_linebreak' => [ + 'only_booleans' => true, + ], + 'ordered_imports' => [ + 'imports_order' => [ + 'class', + 'function', + 'const', + ], + 'sort_algorithm' => 'alpha', + ], + 'php_unit_fqcn_annotation' => true, + 'php_unit_method_casing' => true, + 'phpdoc_align' => true, + 'phpdoc_annotation_without_dot' => true, + 'phpdoc_indent' => true, + 'phpdoc_inline_tag_normalizer' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_alias_tag' => [ + 'replacements' => [ + 'const' => 'var', // @TODO 4.0 add to @PhpdocNoAliasTagFixer defaults + 'link' => 'see', + 'property-read' => 'property', + 'property-write' => 'property', + 'type' => 'var', + ], + ], + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_order' => [ + 'order' => [ + 'param', + 'return', + 'throws', + ], + ], + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => [ + 'types' => [ // @TODO v4 drop custom config with => true, as v4 defaults are same + 'boolean', + 'callback', + 'double', + 'integer', + 'never-return', + 'never-returns', + 'no-return', + 'real', + 'str', + ], + ], + 'phpdoc_separation' => [ + 'groups' => [ + ['Annotation', 'NamedArgumentConstructor', 'Target'], + ...PhpdocSeparationFixer::OPTION_GROUPS_DEFAULT, + ], + 'skip_unlisted_annotations' => false, // @TODO: default value of this option changed, consider to switch to new default + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_summary' => true, + 'phpdoc_tag_type' => [ + 'tags' => [ + 'inheritDoc' => 'inline', + ], + ], + 'phpdoc_to_comment' => [ + 'allow_before_return_statement' => false, // @TODO: default value of this option changed, consider to switch to new default + ], + 'phpdoc_trim' => true, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_types' => true, + 'phpdoc_types_order' => [ + 'null_adjustment' => 'always_last', + 'sort_algorithm' => 'none', + ], + 'phpdoc_var_annotation_correct_order' => true, + 'phpdoc_var_without_name' => true, + 'protected_to_private' => true, + 'semicolon_after_instruction' => true, + 'simple_to_complex_string_variable' => true, + 'single_import_per_statement' => true, + 'single_line_comment_spacing' => true, + 'single_line_comment_style' => [ + 'comment_types' => [ + 'hash', + ], + ], + 'single_line_empty_body' => false, // overrides @PER-CS2.0 + 'single_line_throw' => true, + 'single_quote' => true, + 'single_space_around_construct' => true, + 'space_after_semicolon' => [ + 'remove_in_empty_for_expressions' => true, + ], + 'standardize_increment' => true, + 'standardize_not_equals' => true, + 'statement_indentation' => [ + 'stick_comment_to_next_continuous_control_statement' => true, + ], + 'switch_continue_to_break' => true, + 'trailing_comma_in_multiline' => [ + 'after_heredoc' => true, + 'elements' => [ // explicitly omit 'arguments' + 'array_destructuring', + 'arrays', + 'match', + 'parameters', + ], + ], + 'trim_array_spaces' => true, + 'type_declaration_spaces' => [ + 'elements' => ['function', 'property'], // @TODO v4.0 and before consider to add 'constant' (default value) + ], + 'unary_operator_spaces' => true, + 'whitespace_after_comma_in_array' => true, + 'yoda_style' => true, + ]; + } + + public function getDescription(): string + { + return 'Rules that follow the official `Symfony Coding Standards `_. Extends ``@PER-CS``.'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSetNameValidator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSetNameValidator.php new file mode 100644 index 0000000..2f3eeac --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/RuleSetNameValidator.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RuleSetNameValidator +{ + public static function isValid(string $name, bool $isCustom): bool + { + if (!$isCustom) { + return Preg::match('/^@[a-z][a-z0-9\/_\-\.]*(:risky)?$/i', $name); + } + + // See: https://regex101.com/r/VcOnNr/7 + return Preg::match('/^@(?!PhpCsFixer)[a-z][a-z0-9_]*\/[a-z][a-z0-9_\-\.]*(:risky)?$/i', $name); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/AnalysisStarted.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/AnalysisStarted.php new file mode 100644 index 0000000..707403a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/AnalysisStarted.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Event; + +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Event that is fired when Fixer starts analysis. + * + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AnalysisStarted extends Event +{ + public const NAME = 'fixer.analysis_started'; + public const MODE_SEQUENTIAL = 'sequential'; + public const MODE_PARALLEL = 'parallel'; + + /** @var self::MODE_* */ + private string $mode; + private bool $dryRun; + + /** + * @param self::MODE_* $mode + */ + public function __construct(string $mode, bool $dryRun) + { + $this->mode = $mode; + $this->dryRun = $dryRun; + } + + public function getMode(): string + { + return $this->mode; + } + + public function isDryRun(): bool + { + return $this->dryRun; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/FileProcessed.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/FileProcessed.php new file mode 100644 index 0000000..6fa8426 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Event/FileProcessed.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Event; + +use Symfony\Contracts\EventDispatcher\Event; + +/** + * Event that is fired when file was processed by Fixer. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileProcessed extends Event +{ + /** + * Event name. + */ + public const NAME = 'fixer.file_processed'; + + public const STATUS_INVALID = 1; + public const STATUS_SKIPPED = 2; + public const STATUS_NO_CHANGES = 3; + public const STATUS_FIXED = 4; + public const STATUS_EXCEPTION = 5; + public const STATUS_LINT = 6; + public const STATUS_NON_MONOLITHIC = 7; + + /** + * @var self::STATUS_* + */ + private int $status; + + private ?string $fileHash; + + /** + * @param self::STATUS_* $status + */ + public function __construct(int $status, ?string $fileHash = null) + { + $this->status = $status; + $this->fileHash = $fileHash; + } + + /** + * @return self::STATUS_* + */ + public function getStatus(): int + { + return $this->status; + } + + public function getFileHash(): ?string + { + return $this->fileHash; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingFileIterator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingFileIterator.php new file mode 100644 index 0000000..ae98362 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingFileIterator.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; + +/** + * @internal + * + * @extends \CachingIterator> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileCachingLintingFileIterator extends \CachingIterator implements LintingResultAwareFileIteratorInterface +{ + private LinterInterface $linter; + private ?LintingResultInterface $currentResult = null; + private ?LintingResultInterface $nextResult = null; + + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + + $this->linter = $linter; + } + + public function currentLintingResult(): ?LintingResultInterface + { + return $this->currentResult; + } + + public function next(): void + { + parent::next(); + + $this->currentResult = $this->nextResult; + + if ($this->hasNext()) { + $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); + } + } + + public function rewind(): void + { + parent::rewind(); + + if ($this->valid()) { + $this->currentResult = $this->handleItem($this->current()); + } + + if ($this->hasNext()) { + $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); + } + } + + private function handleItem(\SplFileInfo $file): LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php new file mode 100644 index 0000000..7a88e55 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php @@ -0,0 +1,112 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\FileReader; +use PhpCsFixer\Runner\Event\FileProcessed; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * @internal + * + * @extends \FilterIterator> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FileFilterIterator extends \FilterIterator +{ + private ?EventDispatcherInterface $eventDispatcher; + + private CacheManagerInterface $cacheManager; + + /** + * @var array + */ + private array $visitedElements = []; + + /** + * @param iterable<\SplFileInfo> $iterator + */ + public function __construct( + iterable $iterator, + ?EventDispatcherInterface $eventDispatcher, + CacheManagerInterface $cacheManager + ) { + if (!$iterator instanceof \Iterator) { + $iterator = new \IteratorIterator( + $iterator instanceof \Traversable ? $iterator : new \ArrayIterator($iterator), + ); + } + + parent::__construct($iterator); + + $this->eventDispatcher = $eventDispatcher; + $this->cacheManager = $cacheManager; + } + + public function accept(): bool + { + $file = $this->current(); + if (!$file instanceof \SplFileInfo) { + throw new \RuntimeException( + \sprintf( + 'Expected instance of "\SplFileInfo", got "%s".', + get_debug_type($file), + ), + ); + } + + $path = $file->isLink() ? $file->getPathname() : $file->getRealPath(); + + if (isset($this->visitedElements[$path])) { + return false; + } + + $this->visitedElements[$path] = true; + + if (!$file->isFile() || $file->isLink()) { + return false; + } + + $content = FileReader::createSingleton()->read($path); + + // mark as skipped: + if ( + // empty file + '' === $content + // file that does not need fixing due to cache + || !$this->cacheManager->needFixing($file->getPathname(), $content) + ) { + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed(FileProcessed::STATUS_SKIPPED)); + + return false; + } + + return true; + } + + private function dispatchEvent(string $name, Event $event): void + { + if (null === $this->eventDispatcher) { + return; + } + + $this->eventDispatcher->dispatch($event, $name); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingFileIterator.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingFileIterator.php new file mode 100644 index 0000000..4de06d9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingFileIterator.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; + +/** + * @internal + * + * @extends \IteratorIterator> + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class LintingFileIterator extends \IteratorIterator implements LintingResultAwareFileIteratorInterface +{ + private ?LintingResultInterface $currentResult = null; + + private LinterInterface $linter; + + /** + * @param \Traversable $iterator + */ + public function __construct(\Traversable $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + + $this->linter = $linter; + } + + public function currentLintingResult(): ?LintingResultInterface + { + return $this->currentResult; + } + + public function next(): void + { + parent::next(); + + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + + public function rewind(): void + { + parent::rewind(); + + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + + private function handleItem(\SplFileInfo $file): LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingResultAwareFileIteratorInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingResultAwareFileIteratorInterface.php new file mode 100644 index 0000000..bcaf63f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/LintingResultAwareFileIteratorInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LintingResultInterface; + +/** + * @internal + * + * @extends \Iterator + * + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface LintingResultAwareFileIteratorInterface extends \Iterator +{ + public function currentLintingResult(): ?LintingResultInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelAction.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelAction.php new file mode 100644 index 0000000..0584115 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelAction.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ParallelAction +{ + // Actions executed by the runner (main process) + public const RUNNER_REQUEST_ANALYSIS = 'requestAnalysis'; + public const RUNNER_THANK_YOU = 'thankYou'; + + // Actions executed by the worker + public const WORKER_ERROR_REPORT = 'errorReport'; + public const WORKER_GET_FILE_CHUNK = 'getFileChunk'; + public const WORKER_HELLO = 'hello'; + public const WORKER_RESULT = 'result'; + + private function __construct() {} +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfig.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfig.php new file mode 100644 index 0000000..99faa9a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfig.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * @author Greg Korba + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ParallelConfig +{ + /** @internal */ + public const DEFAULT_FILES_PER_PROCESS = 10; + + /** @internal */ + public const DEFAULT_PROCESS_TIMEOUT = 120; + + private int $filesPerProcess; + private int $maxProcesses; + private int $processTimeout; + + /** + * @param positive-int $maxProcesses + * @param positive-int $filesPerProcess + * @param positive-int $processTimeout + */ + public function __construct( + int $maxProcesses = 2, + int $filesPerProcess = self::DEFAULT_FILES_PER_PROCESS, + int $processTimeout = self::DEFAULT_PROCESS_TIMEOUT + ) { + if ($maxProcesses <= 0 || $filesPerProcess <= 0 || $processTimeout <= 0) { + throw new \InvalidArgumentException('Invalid parallelisation configuration: only positive integers are allowed'); + } + + $this->maxProcesses = $maxProcesses; + $this->filesPerProcess = $filesPerProcess; + $this->processTimeout = $processTimeout; + } + + public function getFilesPerProcess(): int + { + return $this->filesPerProcess; + } + + public function getMaxProcesses(): int + { + return $this->maxProcesses; + } + + public function getProcessTimeout(): int + { + return $this->processTimeout; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfigFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfigFactory.php new file mode 100644 index 0000000..3fdc589 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelConfigFactory.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +use Fidry\CpuCoreCounter\CpuCoreCounter; +use Fidry\CpuCoreCounter\Finder\DummyCpuCoreFinder; +use Fidry\CpuCoreCounter\Finder\FinderRegistry; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ParallelConfigFactory +{ + private static ?CpuCoreCounter $cpuDetector = null; + + private function __construct() {} + + public static function sequential(): ParallelConfig + { + return new ParallelConfig(1); + } + + /** + * @param null|positive-int $filesPerProcess + * @param null|positive-int $processTimeout + * @param null|positive-int $maxProcesses + */ + public static function detect( + ?int $filesPerProcess = null, + ?int $processTimeout = null, + ?int $maxProcesses = null + ): ParallelConfig { + if (null === self::$cpuDetector) { + self::$cpuDetector = new CpuCoreCounter([ + ...FinderRegistry::getDefaultLogicalFinders(), + new DummyCpuCoreFinder(1), + ]); + } + + // Reserve 1 core for the main orchestrating process + $available = self::$cpuDetector->getAvailableForParallelisation(1, $maxProcesses); + + return new ParallelConfig( + $available->availableCpus, + $filesPerProcess ?? ParallelConfig::DEFAULT_FILES_PER_PROCESS, + $processTimeout ?? ParallelConfig::DEFAULT_PROCESS_TIMEOUT, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelisationException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelisationException.php new file mode 100644 index 0000000..19682f6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ParallelisationException.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * Common exception for all the errors related to parallelisation. + * + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ParallelisationException extends \RuntimeException +{ + public static function forUnknownIdentifier(ProcessIdentifier $identifier): self + { + return new self('Unknown process identifier: '.$identifier->toString()); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/Process.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/Process.php new file mode 100644 index 0000000..81c6189 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/Process.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +use React\ChildProcess\Process as ReactProcess; +use React\EventLoop\LoopInterface; +use React\EventLoop\TimerInterface; +use React\Stream\ReadableStreamInterface; +use React\Stream\WritableStreamInterface; + +/** + * Represents single process that is handled within parallel run. + * Inspired by: + * - https://github.com/phpstan/phpstan-src/blob/9ce425bca5337039fb52c0acf96a20a2b8ace490/src/Parallel/Process.php + * - https://github.com/phpstan/phpstan-src/blob/1477e752b4b5893f323b6d2c43591e68b3d85003/src/Process/ProcessHelper.php. + * + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Process +{ + // Properties required for process instantiation + private string $command; + private LoopInterface $loop; + private int $timeoutSeconds; + + // Properties required for process execution + private ?ReactProcess $process = null; + private ?WritableStreamInterface $in = null; + + /** @var resource */ + private $stdErr; + + /** @var resource */ + private $stdOut; + + /** @var callable(array): void */ + private $onData; + + /** @var callable(\Throwable): void */ + private $onError; + + private ?TimerInterface $timer = null; + + public function __construct(string $command, LoopInterface $loop, int $timeoutSeconds) + { + $this->command = $command; + $this->loop = $loop; + $this->timeoutSeconds = $timeoutSeconds; + } + + /** + * @param callable(array $json): void $onData callback to be called when data is received from the parallelisation operator + * @param callable(\Throwable $exception): void $onError callback to be called when an exception occurs + * @param callable(?int $exitCode, string $output): void $onExit callback to be called when the process exits + */ + public function start(callable $onData, callable $onError, callable $onExit): void + { + $sysTempDir = sys_get_temp_dir(); + if (!is_writable($sysTempDir)) { + throw new ParallelisationException(\sprintf( + 'Failed creating temp file as sys_get_temp_dir="%s" is not writable.', + $sysTempDir, + )); + } + + $stdOut = tmpfile(); + if (false === $stdOut) { + throw new ParallelisationException('Failed creating temp file for stdOut.'); + } + $this->stdOut = $stdOut; + + $stdErr = tmpfile(); + if (false === $stdErr) { + throw new ParallelisationException('Failed creating temp file for stdErr.'); + } + $this->stdErr = $stdErr; + + $this->onData = $onData; + $this->onError = $onError; + + $this->process = new ReactProcess($this->command, null, null, [ + 1 => $this->stdOut, + 2 => $this->stdErr, + ]); + $this->process->start($this->loop); + $this->process->on('exit', function ($exitCode) use ($onExit): void { + $this->cancelTimer(); + + $output = ''; + rewind($this->stdOut); + $stdOut = stream_get_contents($this->stdOut); + if (\is_string($stdOut)) { + $output .= $stdOut; + } + + rewind($this->stdErr); + $stdErr = stream_get_contents($this->stdErr); + if (\is_string($stdErr)) { + $output .= $stdErr; + } + + $onExit($exitCode, $output); + + fclose($this->stdOut); + fclose($this->stdErr); + }); + } + + /** + * Handles requests from parallelisation operator to its worker (spawned process). + * + * @param array $data + */ + public function request(array $data): void + { + $this->cancelTimer(); // Configured process timeout actually means "chunk timeout" (each request resets timer) + + if (null === $this->in) { + throw new ParallelisationException( + 'Process not connected with parallelisation operator, ensure `bindConnection()` was called', + ); + } + + $this->in->write($data); + $this->timer = $this->loop->addTimer($this->timeoutSeconds, function (): void { + ($this->onError)( + new \Exception( + \sprintf( + 'Child process timed out after %d seconds. Try making it longer using `ParallelConfig`.', + $this->timeoutSeconds, + ), + ) + ); + }); + } + + public function quit(): void + { + $this->cancelTimer(); + if (null === $this->process || !$this->process->isRunning()) { + return; + } + + foreach ($this->process->pipes as $pipe) { + $pipe->close(); + } + + if (null === $this->in) { + return; + } + + $this->in->end(); + } + + public function bindConnection(ReadableStreamInterface $out, WritableStreamInterface $in): void + { + $this->in = $in; + + $in->on('error', function (\Throwable $error): void { + ($this->onError)($error); + }); + + $out->on('data', function (array $json): void { + $this->cancelTimer(); + + // Pass everything to the parallelisation operator, it should decide how to handle the data + ($this->onData)($json); + }); + $out->on('error', function (\Throwable $error): void { + ($this->onError)($error); + }); + } + + private function cancelTimer(): void + { + if (null === $this->timer) { + return; + } + + $this->loop->cancelTimer($this->timer); + $this->timer = null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessFactory.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessFactory.php new file mode 100644 index 0000000..4c5c6b6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessFactory.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +use PhpCsFixer\Runner\RunnerConfig; +use React\EventLoop\LoopInterface; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Process\PhpExecutableFinder; + +/** + * @author Greg Korba + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessFactory +{ + public function create( + LoopInterface $loop, + InputInterface $input, + RunnerConfig $runnerConfig, + ProcessIdentifier $identifier, + int $serverPort + ): Process { + $commandArgs = $this->getCommandArgs($serverPort, $identifier, $input, $runnerConfig); + + return new Process( + implode(' ', $commandArgs), + $loop, + $runnerConfig->getParallelConfig()->getProcessTimeout(), + ); + } + + /** + * @private + * + * @return non-empty-list + */ + public function getCommandArgs(int $serverPort, ProcessIdentifier $identifier, InputInterface $input, RunnerConfig $runnerConfig): array + { + $phpBinary = (new PhpExecutableFinder())->find(false); + + if (false === $phpBinary) { + throw new ParallelisationException('Cannot find PHP executable.'); + } + + $mainScript = realpath(__DIR__.'/../../../php-cs-fixer'); + if (false === $mainScript + && isset($_SERVER['argv'][0]) + && str_contains($_SERVER['argv'][0], 'php-cs-fixer') + ) { + $mainScript = $_SERVER['argv'][0]; + } + + if (!is_file($mainScript)) { + throw new ParallelisationException('Cannot determine Fixer executable.'); + } + + $commandArgs = [ + ProcessUtils::escapeArgument($phpBinary), + ProcessUtils::escapeArgument($mainScript), + 'worker', + \sprintf('--port=%s', (string) $serverPort), + \sprintf('--identifier=%s', ProcessUtils::escapeArgument($identifier->toString())), + ]; + + if ($runnerConfig->isDryRun()) { + $commandArgs[] = '--dry-run'; + } + + if (filter_var($input->getOption('diff'), \FILTER_VALIDATE_BOOLEAN)) { + $commandArgs[] = '--diff'; + } + + if (filter_var($input->getOption('stop-on-violation'), \FILTER_VALIDATE_BOOLEAN)) { + $commandArgs[] = '--stop-on-violation'; + } + + foreach (['allow-risky', 'config', 'rules', 'using-cache', 'cache-file'] as $option) { + $optionValue = $input->getOption($option); + + if (null !== $optionValue) { + $commandArgs[] = \sprintf('--%s=%s', $option, ProcessUtils::escapeArgument($optionValue)); + } + } + + return $commandArgs; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessIdentifier.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessIdentifier.php new file mode 100644 index 0000000..eeb4534 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessIdentifier.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * Represents identifier of single process that is handled within parallel run. + * + * @author Greg Korba + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessIdentifier +{ + private const IDENTIFIER_PREFIX = 'php-cs-fixer_parallel_'; + + private string $identifier; + + private function __construct(string $identifier) + { + $this->identifier = $identifier; + } + + public function toString(): string + { + return $this->identifier; + } + + public static function create(): self + { + return new self(uniqid(self::IDENTIFIER_PREFIX, true)); + } + + public static function fromRaw(string $identifier): self + { + if (!str_starts_with($identifier, self::IDENTIFIER_PREFIX)) { + throw new ParallelisationException(\sprintf('Invalid process identifier "%s".', $identifier)); + } + + return new self($identifier); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessPool.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessPool.php new file mode 100644 index 0000000..6b64c4f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessPool.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +use React\Socket\ServerInterface; + +/** + * Represents collection of active processes that are being run in parallel. + * Inspired by {@see https://github.com/phpstan/phpstan-src/blob/ed68345a82992775112acc2c2bd639d1bd3a1a02/src/Parallel/ProcessPool.php}. + * + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessPool +{ + /** + * @readonly + */ + private ServerInterface $server; + + /** + * @var null|(callable(): void) + * + * @readonly + */ + private $onServerClose; + + /** + * @var array + */ + private array $processes = []; + + /** + * @param null|(callable(): void) $onServerClose + */ + public function __construct(ServerInterface $server, ?callable $onServerClose = null) + { + $this->server = $server; + $this->onServerClose = $onServerClose; + } + + public function getProcess(ProcessIdentifier $identifier): Process + { + if (!isset($this->processes[$identifier->toString()])) { + throw ParallelisationException::forUnknownIdentifier($identifier); + } + + return $this->processes[$identifier->toString()]; + } + + public function addProcess(ProcessIdentifier $identifier, Process $process): void + { + $this->processes[$identifier->toString()] = $process; + } + + public function endProcessIfKnown(ProcessIdentifier $identifier): void + { + if (!isset($this->processes[$identifier->toString()])) { + return; + } + + $this->endProcess($identifier); + } + + public function endAll(): void + { + foreach ($this->processes as $identifier => $process) { + $this->endProcessIfKnown(ProcessIdentifier::fromRaw($identifier)); + } + } + + private function endProcess(ProcessIdentifier $identifier): void + { + $this->getProcess($identifier)->quit(); + + unset($this->processes[$identifier->toString()]); + + if (0 === \count($this->processes)) { + $this->server->close(); + + if (null !== $this->onServerClose) { + ($this->onServerClose)(); + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessUtils.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessUtils.php new file mode 100644 index 0000000..263d8ef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/ProcessUtils.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This file was copied (and slightly modified) from Symfony: + * - https://github.com/symfony/symfony/blob/3.4/src/Symfony/Component/Process/ProcessUtils.php#L41 + * - (c) Fabien Potencier + * - For the full copyright and license information, please see https://github.com/symfony/symfony/blob/3.4/src/Symfony/Component/Process/LICENSE + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ProcessUtils +{ + /** + * This class should not be instantiated. + */ + private function __construct() {} + + /** + * Escapes a string to be used as a shell argument. + * + * @param string $argument The argument that will be escaped + * + * @return string The escaped argument + */ + public static function escapeArgument(string $argument): string + { + // Fix for PHP bug #43784 escapeshellarg removes % from given string + // Fix for PHP bug #49446 escapeshellarg doesn't work on Windows + // @see https://bugs.php.net/43784 + // @see https://bugs.php.net/49446 + if ('\\' === \DIRECTORY_SEPARATOR) { + if ('' === $argument) { + return escapeshellarg($argument); + } + + $escapedArgument = ''; + $quote = false; + foreach (preg_split('/(")/', $argument, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE) as $part) { // @phpstan-ignore foreach.nonIterable + if ('"' === $part) { + $escapedArgument .= '\"'; + } elseif (self::isSurroundedBy($part, '%')) { + // Avoid environment variable expansion + $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%'; + } else { + // escape trailing backslash + if ('\\' === substr($part, -1)) { + $part .= '\\'; + } + $quote = true; + $escapedArgument .= $part; + } + } + if ($quote) { + $escapedArgument = '"'.$escapedArgument.'"'; + } + + return $escapedArgument; + } + + return "'".str_replace("'", "'\\''", $argument)."'"; + } + + private static function isSurroundedBy(string $arg, string $char): bool + { + return 2 < \strlen($arg) && $char === $arg[0] && $char === $arg[\strlen($arg) - 1]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/WorkerException.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/WorkerException.php new file mode 100644 index 0000000..4b88e68 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Parallel/WorkerException.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner\Parallel; + +/** + * @author Greg Korba + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WorkerException extends \RuntimeException +{ + private string $originalTraceAsString; + + private function __construct(string $message, int $code) + { + parent::__construct($message, $code); + } + + /** + * @param array{ + * class: class-string<\Throwable>, + * message: string, + * file: string, + * line: int, + * code: int, + * trace: string, + * ... + * } $data + */ + public static function fromRaw(array $data): self + { + $exception = new self( + \sprintf('[%s] %s', $data['class'], $data['message']), + $data['code'], + ); + $exception->file = $data['file']; + $exception->line = $data['line']; + $exception->originalTraceAsString = \sprintf( + '## %s(%d)%s%s', + $data['file'], + $data['line'], + \PHP_EOL, + $data['trace'], + ); + + return $exception; + } + + public function getOriginalTraceAsString(): string + { + return $this->originalTraceAsString; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php new file mode 100644 index 0000000..2d3d5fa --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php @@ -0,0 +1,805 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use Clue\React\NDJson\Decoder; +use Clue\React\NDJson\Encoder; +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\Cache\Directory; +use PhpCsFixer\Cache\DirectoryInterface; +use PhpCsFixer\Config\NullRuleCustomisationPolicy; +use PhpCsFixer\Config\RuleCustomisationPolicyInterface; +use PhpCsFixer\Console\Command\WorkerCommand; +use PhpCsFixer\Differ\DifferInterface; +use PhpCsFixer\Error\Error; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\Error\SourceExceptionFactory; +use PhpCsFixer\FileReader; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Future; +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingException; +use PhpCsFixer\Linter\LintingResultInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Runner\Event\AnalysisStarted; +use PhpCsFixer\Runner\Event\FileProcessed; +use PhpCsFixer\Runner\Parallel\ParallelAction; +use PhpCsFixer\Runner\Parallel\ParallelConfig; +use PhpCsFixer\Runner\Parallel\ParallelConfigFactory; +use PhpCsFixer\Runner\Parallel\ParallelisationException; +use PhpCsFixer\Runner\Parallel\ProcessFactory; +use PhpCsFixer\Runner\Parallel\ProcessIdentifier; +use PhpCsFixer\Runner\Parallel\ProcessPool; +use PhpCsFixer\Runner\Parallel\WorkerException; +use PhpCsFixer\Tokenizer\Analyzer\FixerAnnotationAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +use React\EventLoop\StreamSelectLoop; +use React\Socket\ConnectionInterface; +use React\Socket\TcpServer; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Contracts\EventDispatcher\Event; + +/** + * @phpstan-type _RunResult array, diff: string}> + * + * @author Dariusz Rumiński + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @TODO v4: decide if marking Runner as internal or making it dependencies public + * + * @phpstan-ignore-next-line phpCsFixer.internalTypeInPublicApi + */ +final class Runner +{ + /** + * Buffer size used in the NDJSON decoder for communication between main process and workers. + * + * @see https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/8068 + */ + private const PARALLEL_BUFFER_SIZE = 16 * (1_024 * 1_024 /* 1MB */); + + private DifferInterface $differ; + + private DirectoryInterface $directory; + + private ?EventDispatcherInterface $eventDispatcher; + + private ErrorsManager $errorsManager; + + private CacheManagerInterface $cacheManager; + + private bool $isDryRun; + + private LinterInterface $linter; + + /** + * @var null|\Traversable + */ + private ?\Traversable $fileIterator = null; + + private int $fileCount; + + /** + * @var array key is process identifier, value is memory usage in bytes + */ + private array $workersMemoryUsageByProcess = []; + + /** + * @var list + */ + private array $fixers; + + /** + * @var array + */ + private array $fixersByName; + + private bool $stopOnViolation; + + private ParallelConfig $parallelConfig; + + private ?InputInterface $input; + + private ?string $configFile; + + private RuleCustomisationPolicyInterface $ruleCustomisationPolicy; + + /** + * @param null|\Traversable $fileIterator + * @param list $fixers + */ + public function __construct( + ?\Traversable $fileIterator, + array $fixers, + DifferInterface $differ, + ?EventDispatcherInterface $eventDispatcher, + ErrorsManager $errorsManager, + LinterInterface $linter, + bool $isDryRun, + CacheManagerInterface $cacheManager, + ?DirectoryInterface $directory = null, + bool $stopOnViolation = false, + // @TODO Make these arguments required in 4.0 + ?ParallelConfig $parallelConfig = null, + ?InputInterface $input = null, + ?string $configFile = null, + ?RuleCustomisationPolicyInterface $ruleCustomisationPolicy = null + ) { + // Required only for main process (calculating workers count) + $this->fileCount = null !== $fileIterator ? \count(iterator_to_array($fileIterator)) : 0; + + $this->fileIterator = $fileIterator; + $this->fixers = $fixers; + $this->fixersByName = array_reduce( + $fixers, + static function (array $carry, FixerInterface $fixer): array { + $carry[$fixer->getName()] = $fixer; + + return $carry; + }, + [], + ); + $this->differ = $differ; + $this->eventDispatcher = $eventDispatcher; + $this->errorsManager = $errorsManager; + $this->linter = $linter; + $this->isDryRun = $isDryRun; + $this->cacheManager = $cacheManager; + $this->directory = $directory ?? new Directory(''); + $this->stopOnViolation = $stopOnViolation; + $this->parallelConfig = $parallelConfig ?? ParallelConfigFactory::detect(); + $this->input = $input; + $this->configFile = $configFile; + $this->ruleCustomisationPolicy = $ruleCustomisationPolicy ?? new NullRuleCustomisationPolicy(); + } + + /** + * Total workers memory. 0 if not run in parallel mode. + */ + public function getWorkersMemoryUsage(): int + { + return array_sum($this->workersMemoryUsageByProcess); + } + + /** + * @param \Traversable $fileIterator + * + * @TODO v4: mark internal + * @TODO consider to drop this method and make iterator parameter obligatory in constructor, + * more in https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/7777/files#r1590447581 + */ + public function setFileIterator(iterable $fileIterator): void + { + $this->fileIterator = $fileIterator instanceof \Traversable ? $fileIterator : new \ArrayIterator($fileIterator); + + // Required only for main process (calculating workers count) + $this->fileCount = \count(iterator_to_array($fileIterator)); + } + + /** + * @return _RunResult + */ + public function fix(): array + { + if (0 === $this->fileCount) { + return []; + } + + $ruleCustomisers = $this->ruleCustomisationPolicy->getRuleCustomisers(); + $this->validateRulesNamesForExceptions( + array_keys($ruleCustomisers), + <<<'EOT' + Rule Customisation Policy contains customisers for rules that are not in the current set of enabled rules: + %s + + Please check your configuration to ensure that these rules are included, or update your Rule Customisation Policy if they have been replaced by other rules in the version of PHP CS Fixer you are using. + EOT, + ); + + // @TODO 4.0: Remove condition and its body, as no longer needed when param will be required in the constructor. + // This is a fallback only in case someone calls `new Runner()` in a custom repo and does not provide v4-ready params in v3-codebase. + if (null === $this->input) { + return $this->fixSequential(); + } + + if ( + 1 === $this->parallelConfig->getMaxProcesses() + || $this->fileCount <= $this->parallelConfig->getFilesPerProcess() + ) { + return $this->fixSequential(); + } + + return $this->fixParallel(); + } + + /** + * @param list $ruleExceptions + * @param non-empty-string $errorTemplate + */ + private function validateRulesNamesForExceptions(array $ruleExceptions, string $errorTemplate): void + { + if (true === filter_var(getenv('PHP_CS_FIXER_IGNORE_MISMATCHED_RULES_EXCEPTIONS'), \FILTER_VALIDATE_BOOLEAN)) { + return; + } + + if ([] === $ruleExceptions) { + return; + } + + $fixersByName = $this->fixersByName; + $usedRules = array_keys($fixersByName); + $missingRuleNames = array_diff($ruleExceptions, $usedRules); + + if ([] === $missingRuleNames) { + return; + } + + /** @TODO v3.999 check if rule is deprecated and show the replacement rules as well */ + $missingRulesDesc = implode("\n", array_map( + static function (string $name) use ($fixersByName): string { + $extra = ''; + if ('' === $name) { + $extra = '(no name provided)'; + } elseif ('@' === $name[0]) { + $extra = ' (can exclude only rules, not sets)'; + } elseif (!isset($fixersByName[$name])) { + $extra = ' (unknown rule)'; + } + + return '- '.$name.$extra; + }, + $missingRuleNames, + )); + + throw new \RuntimeException( + \sprintf($errorTemplate, $missingRulesDesc), + ); + } + + /** + * Heavily inspired by {@see https://github.com/phpstan/phpstan-src/blob/9ce425bca5337039fb52c0acf96a20a2b8ace490/src/Parallel/ParallelAnalyser.php}. + * + * @return _RunResult + */ + private function fixParallel(): array + { + $this->dispatchEvent(AnalysisStarted::NAME, new AnalysisStarted(AnalysisStarted::MODE_PARALLEL, $this->isDryRun)); + + $changed = []; + $streamSelectLoop = new StreamSelectLoop(); + $server = new TcpServer('127.0.0.1:0', $streamSelectLoop); + $serverPort = parse_url($server->getAddress() ?? '', \PHP_URL_PORT); + + if (!is_numeric($serverPort)) { + throw new ParallelisationException(\sprintf( + 'Unable to parse server port from "%s"', + $server->getAddress() ?? '', + )); + } + + $processPool = new ProcessPool( + $server, + static function () use ($streamSelectLoop): void { + $streamSelectLoop->stop(); + }, + ); + $maxFilesPerProcess = $this->parallelConfig->getFilesPerProcess(); + $fileIterator = $this->getFilteringFileIterator(); + $fileIterator->rewind(); + + $getFileChunk = static function () use ($fileIterator, $maxFilesPerProcess): array { + $files = []; + + while (\count($files) < $maxFilesPerProcess) { + $current = $fileIterator->current(); + + if (null === $current) { + break; + } + + $files[] = $current->getPathname(); + + $fileIterator->next(); + } + + return $files; + }; + + // [REACT] Handle worker's handshake (init connection) + $server->on('connection', static function (ConnectionInterface $connection) use ($processPool, $getFileChunk): void { + $decoder = new Decoder( + $connection, + true, + 512, + \JSON_INVALID_UTF8_IGNORE, + self::PARALLEL_BUFFER_SIZE, + ); + $encoder = new Encoder($connection, \JSON_INVALID_UTF8_IGNORE); + + // [REACT] Bind connection when worker's process requests "hello" action (enables 2-way communication) + $decoder->on('data', static function (array $data) use ($processPool, $getFileChunk, $decoder, $encoder): void { + \assert(isset($data['action'])); + + if (ParallelAction::WORKER_HELLO !== $data['action']) { + return; + } + + \assert(isset( + $data['identifier'], + )); + + $identifier = ProcessIdentifier::fromRaw($data['identifier']); + + // Avoid race condition where worker tries to establish connection, + // but runner already ended all processes because `stop-on-violation` mode was enabled. + try { + $process = $processPool->getProcess($identifier); + } catch (ParallelisationException $e) { + return; + } + + $process->bindConnection($decoder, $encoder); + $fileChunk = $getFileChunk(); + + if (0 === \count($fileChunk)) { + $process->request(['action' => ParallelAction::RUNNER_THANK_YOU]); + $processPool->endProcessIfKnown($identifier); + + return; + } + + $process->request(['action' => ParallelAction::RUNNER_REQUEST_ANALYSIS, 'files' => $fileChunk]); + }); + }); + + $processesToSpawn = min( + $this->parallelConfig->getMaxProcesses(), + max( + 1, + (int) ceil($this->fileCount / $this->parallelConfig->getFilesPerProcess()), + ), + ); + $processFactory = new ProcessFactory(); + + for ($i = 0; $i < $processesToSpawn; ++$i) { + $identifier = ProcessIdentifier::create(); + $process = $processFactory->create( + $streamSelectLoop, + $this->input, + new RunnerConfig( + $this->isDryRun, + $this->stopOnViolation, + $this->parallelConfig, + $this->configFile, + ), + $identifier, + $serverPort, + ); + $processPool->addProcess($identifier, $process); + $process->start( + // [REACT] Handle workers' responses (multiple actions possible) + function (array $workerResponse) use ($processPool, $process, $identifier, $getFileChunk, &$changed): void { + \assert(isset($workerResponse['action'])); + + // File analysis result (we want close-to-realtime progress with frequent cache savings) + if (ParallelAction::WORKER_RESULT === $workerResponse['action']) { + \assert(isset( + $workerResponse['errors'], + $workerResponse['file'], + // $workerResponse['fileHash'], // optional + // $workerResponse['fixInfo'], // optional + $workerResponse['memoryUsage'], + $workerResponse['status'], + )); + + // Dispatch an event for each file processed and dispatch its status (required for progress output) + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed($workerResponse['status'])); + + if (isset($workerResponse['fileHash'])) { + $this->cacheManager->setFileHash($workerResponse['file'], $workerResponse['fileHash']); + } + + foreach ($workerResponse['errors'] as $error) { + $this->errorsManager->report(new Error( + $error['type'], + $error['filePath'], + null !== $error['source'] + ? SourceExceptionFactory::fromArray($error['source']) + : null, + $error['appliedFixers'], + $error['diff'], + )); + } + + // we collect memory on each file, as any violation may terminate processPool via stopOnViolation + $this->workersMemoryUsageByProcess[$identifier->toString()] = $workerResponse['memoryUsage']; + + // Pass-back information about applied changes (only if there are any) + if (isset($workerResponse['fixInfo'])) { + $relativePath = $this->directory->getRelativePathTo($workerResponse['file']); + $changed[$relativePath] = $workerResponse['fixInfo']; + + if ($this->stopOnViolation) { + $processPool->endAll(); + + return; + } + } + + return; + } + + if (ParallelAction::WORKER_GET_FILE_CHUNK === $workerResponse['action']) { + // no payload to assert on + + // Request another chunk of files, if still available + $fileChunk = $getFileChunk(); + + if (0 === \count($fileChunk)) { + $process->request(['action' => ParallelAction::RUNNER_THANK_YOU]); + $processPool->endProcessIfKnown($identifier); + + return; + } + + $process->request(['action' => ParallelAction::RUNNER_REQUEST_ANALYSIS, 'files' => $fileChunk]); + + return; + } + + if (ParallelAction::WORKER_ERROR_REPORT === $workerResponse['action']) { + \assert(isset( + $workerResponse['class'], + $workerResponse['message'], + $workerResponse['file'], + $workerResponse['line'], + $workerResponse['code'], + $workerResponse['trace'], + )); + + throw WorkerException::fromRaw($workerResponse); + } + + throw new ParallelisationException('Unsupported action: '.($workerResponse['action'] ?? 'n/a')); + }, + + // [REACT] Handle errors encountered during worker's execution + static function (\Throwable $error) use ($processPool): void { + $processPool->endAll(); + + throw new ParallelisationException($error->getMessage(), $error->getCode(), $error); + }, + + // [REACT] Handle worker's shutdown + static function ($exitCode, string $output) use ($processPool, $identifier): void { + // @codeCoverageIgnoreStart + $processPool->endProcessIfKnown($identifier); + + if (0 === $exitCode || null === $exitCode) { + return; + } + + $errorsReported = Preg::matchAll( + \sprintf('/^(?:%s)([^\n]+)+/m', WorkerCommand::ERROR_PREFIX), + $output, + $matches, + ); + + if ($errorsReported > 0) { + throw WorkerException::fromRaw( + json_decode($matches[1][0], true, 512, \JSON_THROW_ON_ERROR), + ); + } + // @codeCoverageIgnoreEnd + }, + ); + } + + $streamSelectLoop->run(); + + return $changed; + } + + /** + * @return _RunResult + */ + private function fixSequential(): array + { + $this->dispatchEvent(AnalysisStarted::NAME, new AnalysisStarted(AnalysisStarted::MODE_SEQUENTIAL, $this->isDryRun)); + + $changed = []; + $collection = $this->getLintingFileIterator(); + + foreach ($collection as $file) { + $fixInfo = $this->fixFile($file, $collection->currentLintingResult()); + + // we do not need Tokens to still caching just fixed file - so clear the cache + Tokens::clearCache(); + + if (null !== $fixInfo) { + $relativePath = $this->directory->getRelativePathTo($file->__toString()); + $changed[$relativePath] = $fixInfo; + + if ($this->stopOnViolation) { + break; + } + } + } + + return $changed; + } + + /** + * @return null|array{appliedFixers: list, diff: string} + */ + private function fixFile(\SplFileInfo $file, LintingResultInterface $lintingResult): ?array + { + $filePathname = $file->getPathname(); + + try { + $lintingResult->check(); + } catch (LintingException $e) { + $this->dispatchEvent( + FileProcessed::NAME, + new FileProcessed(FileProcessed::STATUS_INVALID), + ); + + $this->errorsManager->report(new Error(Error::TYPE_INVALID, $filePathname, $e)); + + return null; + } + + $old = FileReader::createSingleton()->read($file->getRealPath()); + + $tokens = Tokens::fromCode($old); + + if ( + Future::isFutureModeEnabled() // @TODO 4.0 drop this line + && !filter_var(getenv('PHP_CS_FIXER_NON_MONOLITHIC'), \FILTER_VALIDATE_BOOL) + && !$tokens->isMonolithicPhp() + ) { + $this->dispatchEvent( + FileProcessed::NAME, + new FileProcessed(FileProcessed::STATUS_NON_MONOLITHIC), + ); + + return null; + } + + $oldHash = $tokens->getCodeHash(); + $newHash = $oldHash; + $new = $old; + + $appliedFixers = []; + + $ruleCustomisers = $this->ruleCustomisationPolicy->getRuleCustomisers(); // were already validated + + try { + $fixerAnnotationAnalysis = (new FixerAnnotationAnalyzer())->find($tokens); + $rulesIgnoredByAnnotations = $fixerAnnotationAnalysis['php-cs-fixer-ignore'] ?? []; + } catch (\RuntimeException $e) { + throw new \RuntimeException( + \sprintf( + 'Error while analysing file "%s": %s', + $filePathname, + $e->getMessage(), + ), + $e->getCode(), + $e, + ); + } + + $this->validateRulesNamesForExceptions( + $rulesIgnoredByAnnotations, + <<fixers as $fixer) { + if (\in_array($fixer->getName(), $rulesIgnoredByAnnotations, true)) { + continue; + } + + $customiser = $ruleCustomisers[$fixer->getName()] ?? null; + if (null !== $customiser) { + $actualFixer = $customiser($file); + if (false === $actualFixer) { + continue; + } + if (true !== $actualFixer) { + if (\get_class($fixer) !== \get_class($actualFixer)) { + throw new \RuntimeException(\sprintf( + 'The fixer returned by the Rule Customisation Policy must be of the same class as the original fixer (expected `%s`, got `%s`).', + \get_class($fixer), + \get_class($actualFixer), + )); + } + $fixer = $actualFixer; + } + } + + // for custom fixers we don't know is it safe to run `->fix()` without checking `->supports()` and `->isCandidate()`, + // thus we need to check it and conditionally skip fixing + if ( + !$fixer instanceof AbstractFixer + && (!$fixer->supports($file) || !$fixer->isCandidate($tokens)) + ) { + continue; + } + + $fixer->fix($file, $tokens); + + if ($tokens->isChanged()) { + $tokens->clearEmptyTokens(); + $tokens->clearChanged(); + $appliedFixers[] = $fixer->getName(); + if (filter_var(getenv('PHP_CS_FIXER_DEBUG'), \FILTER_VALIDATE_BOOL)) { + try { + $this->linter->lintSource($tokens->generateCode())->check(); + } catch (LintingException $e) { + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed(FileProcessed::STATUS_LINT)); + + $this->errorsManager->report(new Error(Error::TYPE_LINT, $filePathname, $e, [$fixer->getName()], $this->differ->diff($old, $tokens->generateCode(), $file))); + + return null; + } + } + } + } + } catch (\ParseError $e) { + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed(FileProcessed::STATUS_LINT)); + + $this->errorsManager->report(new Error(Error::TYPE_LINT, $filePathname, $e)); + + return null; + } catch (\Throwable $e) { + $this->processException($filePathname, $e); + + return null; + } + + $fixInfo = null; + + if ([] !== $appliedFixers) { + $new = $tokens->generateCode(); + $newHash = $tokens->getCodeHash(); + } + + // We need to check if content was changed and then applied changes. + // But we can't simply check $appliedFixers, because one fixer may revert + // work of other and both of them will mark collection as changed. + // Therefore we need to check if code hashes changed. + if ($oldHash !== $newHash) { + $fixInfo = [ + 'appliedFixers' => $appliedFixers, + 'diff' => $this->differ->diff($old, $new, $file), + ]; + + try { + $this->linter->lintSource($new)->check(); + } catch (LintingException $e) { + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed(FileProcessed::STATUS_LINT)); + + $this->errorsManager->report(new Error(Error::TYPE_LINT, $filePathname, $e, $fixInfo['appliedFixers'], $fixInfo['diff'])); + + return null; + } + + if (!$this->isDryRun) { + $fileRealPath = $file->getRealPath(); + + if (!file_exists($fileRealPath)) { + throw new IOException( + \sprintf('Failed to write file "%s" (no longer) exists.', $file->getPathname()), + 0, + null, + $file->getPathname(), + ); + } + + if (is_dir($fileRealPath)) { + throw new IOException( + \sprintf('Cannot write file "%s" as the location exists as directory.', $fileRealPath), + 0, + null, + $fileRealPath, + ); + } + + if (!is_writable($fileRealPath)) { + throw new IOException( + \sprintf('Cannot write to file "%s" as it is not writable.', $fileRealPath), + 0, + null, + $fileRealPath, + ); + } + + if (false === @file_put_contents($fileRealPath, $new)) { + $error = error_get_last(); + + throw new IOException( + \sprintf('Failed to write file "%s", "%s".', $fileRealPath, null !== $error ? $error['message'] : 'no reason available'), + 0, + null, + $fileRealPath, + ); + } + } + } + + $this->cacheManager->setFileHash($filePathname, $newHash); + + $this->dispatchEvent( + FileProcessed::NAME, + new FileProcessed(null !== $fixInfo ? FileProcessed::STATUS_FIXED : FileProcessed::STATUS_NO_CHANGES, $newHash), + ); + + return $fixInfo; + } + + /** + * Process an exception that occurred. + */ + private function processException(string $name, \Throwable $e): void + { + $this->dispatchEvent(FileProcessed::NAME, new FileProcessed(FileProcessed::STATUS_EXCEPTION)); + + $this->errorsManager->report(new Error(Error::TYPE_EXCEPTION, $name, $e)); + } + + private function dispatchEvent(string $name, Event $event): void + { + if (null === $this->eventDispatcher) { + return; + } + + $this->eventDispatcher->dispatch($event, $name); + } + + private function getLintingFileIterator(): LintingResultAwareFileIteratorInterface + { + $fileFilterIterator = $this->getFilteringFileIterator(); + + return $this->linter->isAsync() + ? new FileCachingLintingFileIterator($fileFilterIterator, $this->linter) + : new LintingFileIterator($fileFilterIterator, $this->linter); + } + + private function getFilteringFileIterator(): FileFilterIterator + { + if (null === $this->fileIterator) { + throw new \RuntimeException('File iterator is not configured. Pass paths during Runner initialisation or set them after with `setFileIterator()`.'); + } + + return new FileFilterIterator( + $this->fileIterator instanceof \IteratorAggregate + ? $this->fileIterator->getIterator() + : $this->fileIterator, + $this->eventDispatcher, + $this->cacheManager, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/RunnerConfig.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/RunnerConfig.php new file mode 100644 index 0000000..0983c8d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Runner/RunnerConfig.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Runner\Parallel\ParallelConfig; + +/** + * @author Greg Korba + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RunnerConfig +{ + private bool $isDryRun; + private bool $stopOnViolation; + private ParallelConfig $parallelConfig; + private ?string $configFile; + + public function __construct( + bool $isDryRun, + bool $stopOnViolation, + ParallelConfig $parallelConfig, + ?string $configFile = null + ) { + $this->isDryRun = $isDryRun; + $this->stopOnViolation = $stopOnViolation; + $this->parallelConfig = $parallelConfig; + $this->configFile = $configFile; + } + + public function isDryRun(): bool + { + return $this->isDryRun; + } + + public function shouldStopOnViolation(): bool + { + return $this->stopOnViolation; + } + + public function getParallelConfig(): ParallelConfig + { + return $this->parallelConfig; + } + + public function getConfigFile(): ?string + { + return $this->configFile; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php new file mode 100644 index 0000000..c3834ab --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php @@ -0,0 +1,175 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Davi Koscianski Vidal + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class StdinFileInfo extends \SplFileInfo +{ + public function __construct() + { + parent::__construct(__FILE__); + } + + public function __toString(): string + { + return $this->getRealPath(); + } + + public function getRealPath(): string + { + // So file_get_contents & friends will work. + // Warning - this stream is not seekable, so `file_get_contents` will work only once! Consider using `FileReader`. + return 'php://stdin'; + } + + public function getATime(): int + { + return 0; + } + + public function getBasename($suffix = null): string + { + return $this->getFilename(); + } + + public function getCTime(): int + { + return 0; + } + + public function getExtension(): string + { + return '.php'; + } + + /** + * @param null|class-string<\SplFileInfo> $class + */ + public function getFileInfo($class = null): \SplFileInfo + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } + + public function getFilename(): string + { + /* + * Useful so fixers depending on PHP-only files still work. + * + * The idea to use STDIN is to parse PHP-only files, so we can + * assume that there will be always a PHP file out there. + */ + + return 'stdin.php'; + } + + public function getGroup(): int + { + return 0; + } + + public function getInode(): int + { + return 0; + } + + public function getLinkTarget(): string + { + return ''; + } + + public function getMTime(): int + { + return 0; + } + + public function getOwner(): int + { + return 0; + } + + public function getPath(): string + { + return ''; + } + + /** + * @param null|class-string<\SplFileInfo> $class + */ + public function getPathInfo($class = null): \SplFileInfo + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } + + public function getPathname(): string + { + return $this->getFilename(); + } + + public function getPerms(): int + { + return 0; + } + + public function getSize(): int + { + return 0; + } + + public function getType(): string + { + return 'file'; + } + + public function isDir(): bool + { + return false; + } + + public function isExecutable(): bool + { + return false; + } + + public function isFile(): bool + { + return true; + } + + public function isLink(): bool + { + return false; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function openFile($openMode = 'r', $useIncludePath = false, $context = null): \SplFileObject + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php new file mode 100644 index 0000000..d0c632b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Utils; + +/** + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractTransformer implements TransformerInterface +{ + public function getName(): string + { + $nameParts = explode('\\', static::class); + $name = substr(end($nameParts), 0, -\strlen('Transformer')); + + return Utils::camelCaseToUnderscore($name); + } + + public function getPriority(): int + { + return 0; + } + + abstract public function getCustomTokens(): array; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php new file mode 100644 index 0000000..66907f9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * @phpstan-import-type _PhpTokenPrototype from Token + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractTypeTransformer extends AbstractTransformer +{ + private const TYPE_END_TOKENS = [')', [\T_CALLABLE], [\T_NS_SEPARATOR], [\T_STATIC], [\T_STRING], [CT::T_ARRAY_TYPEHINT]]; + + private const TYPE_TOKENS = [ + '|', '&', '(', + ...self::TYPE_END_TOKENS, + [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_INTERSECTION], // some siblings may already be transformed + [\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], // technically these can be inside of type tokens array + ]; + + abstract protected function replaceToken(Tokens $tokens, int $index): void; + + /** + * @param _PhpTokenPrototype $originalToken + */ + protected function doProcess(Tokens $tokens, int $index, $originalToken): void + { + if (!$tokens[$index]->equals($originalToken)) { + return; + } + + if (!$this->isPartOfType($tokens, $index)) { + return; + } + + $this->replaceToken($tokens, $index); + } + + private function isPartOfType(Tokens $tokens, int $index): bool + { + // return types and non-capturing catches + $typeColonIndex = $tokens->getTokenNotOfKindSibling($index, -1, self::TYPE_TOKENS); + if ($tokens[$typeColonIndex]->isGivenKind([\T_CATCH, CT::T_TYPE_COLON, \T_CONST])) { + return true; + } + + // for parameter there will be splat operator or variable after the type ("&" is ambiguous and can be reference or bitwise and) + $afterTypeIndex = $tokens->getTokenNotOfKindSibling($index, 1, self::TYPE_TOKENS); + + if ($tokens[$afterTypeIndex]->isGivenKind(\T_ELLIPSIS)) { + return true; + } + + if (!$tokens[$afterTypeIndex]->isGivenKind(\T_VARIABLE)) { + return false; + } + + $beforeVariableIndex = $tokens->getPrevMeaningfulToken($afterTypeIndex); + if ($tokens[$beforeVariableIndex]->equals('&')) { + $prevIndex = $tokens->getPrevTokenOfKind( + $index, + [ + '{', + '}', + ';', + [\T_CLOSE_TAG], + [\T_FN], + [\T_FUNCTION], + ], + ); + + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]); + } + + return $tokens[$beforeVariableIndex]->equalsAny(self::TYPE_END_TOKENS); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php new file mode 100644 index 0000000..f72443c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @TODO 4.0 remove this analyzer and move this logic into a transformer + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AlternativeSyntaxAnalyzer +{ + private const ALTERNATIVE_SYNTAX_BLOCK_EDGES = [ + \T_IF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], + \T_ELSE => [\T_ENDIF], + \T_ELSEIF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], + \T_FOR => [\T_ENDFOR], + \T_FOREACH => [\T_ENDFOREACH], + \T_WHILE => [\T_ENDWHILE], + \T_SWITCH => [\T_ENDSWITCH], + ]; + + public function belongsToAlternativeSyntax(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_ELSE)) { + return true; + } + + if (!$tokens[$prevIndex]->equals(')')) { + return false; + } + + $openParenthesisIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $prevIndex); + $beforeOpenParenthesisIndex = $tokens->getPrevMeaningfulToken($openParenthesisIndex); + + return $tokens[$beforeOpenParenthesisIndex]->isGivenKind([ + \T_DECLARE, + \T_ELSEIF, + \T_FOR, + \T_FOREACH, + \T_IF, + \T_SWITCH, + \T_WHILE, + ]); + } + + public function findAlternativeSyntaxBlockEnd(Tokens $tokens, int $index): int + { + if (!isset($tokens[$index])) { + throw new \InvalidArgumentException("There is no token at index {$index}."); + } + + if (!$this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + throw new \InvalidArgumentException("Token at index {$index} is not the start of an alternative syntax block."); + } + + $startTokenKind = $tokens[$index]->getId(); + + if (!isset(self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind])) { + throw new \LogicException(\sprintf('Unknown startTokenKind: %s', $tokens[$index]->toJson())); + } + + $endTokenKinds = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind]; + + $findKinds = [[$startTokenKind]]; + foreach ($endTokenKinds as $endTokenKind) { + $findKinds[] = [$endTokenKind]; + } + + while (true) { + $index = $tokens->getNextTokenOfKind($index, $findKinds); + + if ($tokens[$index]->isGivenKind($endTokenKinds)) { + return $index; + } + + if ($this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + $index = $this->findAlternativeSyntaxBlockEnd($tokens, $index); + } + } + } + + private function isStartOfAlternativeSyntaxBlock(Tokens $tokens, int $index): bool + { + $map = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES; + $startTokenKind = $tokens[$index]->getId(); + + if (null === $startTokenKind || !isset($map[$startTokenKind])) { + return false; + } + + $index = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$index]->equals('(')) { + $index = $tokens->getNextMeaningfulToken( + $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index), + ); + } + + return $tokens[$index]->equals(':'); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php new file mode 100644 index 0000000..042a82d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +abstract class AbstractControlCaseStructuresAnalysis +{ + private int $index; + + private int $open; + + private int $close; + + public function __construct(int $index, int $open, int $close) + { + $this->index = $index; + $this->open = $open; + $this->close = $close; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getOpenIndex(): int + { + return $this->open; + } + + public function getCloseIndex(): int + { + return $this->close; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php new file mode 100644 index 0000000..fadcfb3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArgumentAnalysis +{ + /** + * The name of the argument. + */ + private ?string $name; + + /** + * The index where the name is located in the supplied Tokens object. + */ + private ?int $nameIndex; + + /** + * The default value of the argument. + */ + private ?string $default; + + /** + * The type analysis of the argument. + */ + private ?TypeAnalysis $typeAnalysis; + + public function __construct(?string $name, ?int $nameIndex, ?string $default, ?TypeAnalysis $typeAnalysis = null) + { + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->default = $default ?? null; + $this->typeAnalysis = $typeAnalysis ?? null; + } + + public function getDefault(): ?string + { + return $this->default; + } + + public function hasDefault(): bool + { + return null !== $this->default; + } + + public function getName(): ?string + { + return $this->name; + } + + public function getNameIndex(): ?int + { + return $this->nameIndex; + } + + public function getTypeAnalysis(): ?TypeAnalysis + { + return $this->typeAnalysis; + } + + public function hasTypeAnalysis(): bool + { + return null !== $this->typeAnalysis; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AttributeAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AttributeAnalysis.php new file mode 100644 index 0000000..b14c1d3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AttributeAnalysis.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @phpstan-type _AttributeItem array{start: int, end: int, name: string} + * @phpstan-type _AttributeItems non-empty-list<_AttributeItem> + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AttributeAnalysis +{ + private int $startIndex; + private int $endIndex; + private int $openingBracketIndex; + private int $closingBracketIndex; + + /** + * @var _AttributeItems + */ + private array $attributes; + + /** + * @param _AttributeItems $attributes + */ + public function __construct(int $startIndex, int $endIndex, int $openingBracketIndex, int $closingBracketIndex, array $attributes) + { + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->openingBracketIndex = $openingBracketIndex; + $this->closingBracketIndex = $closingBracketIndex; + $this->attributes = $attributes; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function getOpeningBracketIndex(): int + { + return $this->openingBracketIndex; + } + + public function getClosingBracketIndex(): int + { + return $this->closingBracketIndex; + } + + /** + * @return _AttributeItems + */ + public function getAttributes(): array + { + return $this->attributes; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php new file mode 100644 index 0000000..11f6873 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @author Kuba Werłos + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CaseAnalysis +{ + private int $index; + + private int $colonIndex; + + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getColonIndex(): int + { + return $this->colonIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php new file mode 100644 index 0000000..39b3ee5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DataProviderAnalysis +{ + private string $name; + + private int $nameIndex; + + /** @var non-empty-list */ + private array $usageIndices; + + /** + * @param non-empty-list $usageIndices + */ + public function __construct(string $name, int $nameIndex, array $usageIndices) + { + if ([] === $usageIndices || !array_is_list($usageIndices)) { + throw new \InvalidArgumentException( + 'Parameter "usageIndices" should be a non-empty-list.', + ); + } + + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->usageIndices = $usageIndices; + } + + public function getName(): string + { + return $this->name; + } + + public function getNameIndex(): int + { + return $this->nameIndex; + } + + /** + * @return non-empty-list + */ + public function getUsageIndices(): array + { + return $this->usageIndices; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php new file mode 100644 index 0000000..550dba9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DefaultAnalysis +{ + private int $index; + + private int $colonIndex; + + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + + public function getIndex(): int + { + return $this->index; + } + + public function getColonIndex(): int + { + return $this->colonIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php new file mode 100644 index 0000000..df68325 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class EnumAnalysis extends AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private array $cases; + + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases) + { + parent::__construct($index, $open, $close); + + $this->cases = $cases; + } + + /** + * @return list + */ + public function getCases(): array + { + return $this->cases; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php new file mode 100644 index 0000000..3472ba3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class MatchAnalysis extends AbstractControlCaseStructuresAnalysis +{ + private ?DefaultAnalysis $defaultAnalysis; + + public function __construct(int $index, int $open, int $close, ?DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + + $this->defaultAnalysis = $defaultAnalysis; + } + + public function getDefaultAnalysis(): ?DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php new file mode 100644 index 0000000..9336ce7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @TODO v4: previously was mareked as internal - yet it leaked to public interface of `DocBlock`, consider making it so again. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamespaceAnalysis +{ + /** + * The fully qualified namespace name. + */ + private string $fullName; + + /** + * The short version of the namespace. + */ + private string $shortName; + + /** + * The start index of the namespace declaration in the analysed Tokens. + */ + private int $startIndex; + + /** + * The end index of the namespace declaration in the analysed Tokens. + */ + private int $endIndex; + + /** + * The start index of the scope of the namespace in the analysed Tokens. + */ + private int $scopeStartIndex; + + /** + * The end index of the scope of the namespace in the analysed Tokens. + */ + private int $scopeEndIndex; + + /** + * @internal + */ + public function __construct(string $fullName, string $shortName, int $startIndex, int $endIndex, int $scopeStartIndex, int $scopeEndIndex) + { + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->scopeStartIndex = $scopeStartIndex; + $this->scopeEndIndex = $scopeEndIndex; + } + + public function getFullName(): string + { + return $this->fullName; + } + + public function getShortName(): string + { + return $this->shortName; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function getScopeStartIndex(): int + { + return $this->scopeStartIndex; + } + + public function getScopeEndIndex(): int + { + return $this->scopeEndIndex; + } + + public function isGlobalNamespace(): bool + { + return '' === $this->getFullName(); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php new file mode 100644 index 0000000..37d9cc7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @TODO v4: previously was mareked as internal - yet it leaked to public interface of `DocBlock`, consider making it so again. + * + * @phpstan-type _ImportType 'class'|'constant'|'function' + * + * @author VeeWee + * @author Greg Korba + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamespaceUseAnalysis +{ + public const TYPE_CLASS = 1; // "classy" could be class, interface or trait + public const TYPE_FUNCTION = 2; + public const TYPE_CONSTANT = 3; + + /** + * The fully qualified use namespace. + * + * @var non-empty-string + */ + private string $fullName; + + /** + * The short version of use namespace or the alias name in case of aliased use statements. + * + * @var non-empty-string + */ + private string $shortName; + + /** + * Is the use statement part of multi-use (`use A, B, C;`, `use A\{B, C};`)? + */ + private bool $isInMulti; + + /** + * Is the use statement being aliased? + */ + private bool $isAliased; + + /** + * The start index of the namespace declaration in the analysed Tokens. + */ + private int $startIndex; + + /** + * The end index of the namespace declaration in the analysed Tokens. + */ + private int $endIndex; + + /** + * The start index of the single import in the multi-use statement. + */ + private ?int $chunkStartIndex; + + /** + * The end index of the single import in the multi-use statement. + */ + private ?int $chunkEndIndex; + + /** + * The type of import: class, function or constant. + * + * @var self::TYPE_* + */ + private int $type; + + /** + * @param self::TYPE_* $type + * @param non-empty-string $fullName + * @param non-empty-string $shortName + * + * @internal + */ + public function __construct( + int $type, + string $fullName, + string $shortName, + bool $isAliased, + bool $isInMulti, + int $startIndex, + int $endIndex, + ?int $chunkStartIndex = null, + ?int $chunkEndIndex = null + ) { + if (true === $isInMulti && (null === $chunkStartIndex || null === $chunkEndIndex)) { + throw new \LogicException('Chunk start and end index must be set when the import is part of a multi-use statement.'); + } + + $this->type = $type; + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->isAliased = $isAliased; + $this->isInMulti = $isInMulti; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->chunkStartIndex = $chunkStartIndex; + $this->chunkEndIndex = $chunkEndIndex; + } + + /** + * @return non-empty-string + */ + public function getFullName(): string + { + return $this->fullName; + } + + /** + * @return non-empty-string + */ + public function getShortName(): string + { + return $this->shortName; + } + + public function isAliased(): bool + { + return $this->isAliased; + } + + public function isInMulti(): bool + { + return $this->isInMulti; + } + + public function getStartIndex(): int + { + return $this->startIndex; + } + + public function getEndIndex(): int + { + return $this->endIndex; + } + + public function getChunkStartIndex(): ?int + { + return $this->chunkStartIndex; + } + + public function getChunkEndIndex(): ?int + { + return $this->chunkEndIndex; + } + + /** + * @return self::TYPE_* + */ + public function getType(): int + { + return $this->type; + } + + /** + * @return _ImportType + */ + public function getHumanFriendlyType(): string + { + return [ + self::TYPE_CLASS => 'class', + self::TYPE_FUNCTION => 'function', + self::TYPE_CONSTANT => 'constant', + ][$this->type]; + } + + public function isClass(): bool + { + return self::TYPE_CLASS === $this->type; + } + + public function isFunction(): bool + { + return self::TYPE_FUNCTION === $this->type; + } + + public function isConstant(): bool + { + return self::TYPE_CONSTANT === $this->type; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php new file mode 100644 index 0000000..d26cd8b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SwitchAnalysis extends AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private array $cases; + + private ?DefaultAnalysis $defaultAnalysis; + + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases, ?DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + + $this->cases = $cases; + $this->defaultAnalysis = $defaultAnalysis; + } + + /** + * @return list + */ + public function getCases(): array + { + return $this->cases; + } + + public function getDefaultAnalysis(): ?DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php new file mode 100644 index 0000000..f2a8f10 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeAnalysis +{ + /** + * This list contains soft and hard reserved types that can be used or will be used by PHP at some point. + * + * More info: + * + * @var non-empty-list + * + * @see https://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.types + * @see https://php.net/manual/en/reserved.other-reserved-words.php + */ + private const RESERVED_TYPES = [ + 'array', + 'bool', + 'callable', + 'false', + 'float', + 'int', + 'iterable', + 'list', + 'mixed', + 'never', + 'null', + 'object', + 'parent', + 'resource', + 'self', + 'static', + 'string', + 'true', + 'void', + ]; + + private string $name; + + private ?int $startIndex; + + private ?int $endIndex; + + private bool $nullable; + + /** + * @param ($startIndex is null ? null : int) $endIndex + */ + public function __construct(string $name, ?int $startIndex = null, ?int $endIndex = null) + { + if (str_starts_with($name, '?')) { + $this->name = substr($name, 1); + $this->nullable = true; + } elseif (\PHP_VERSION_ID >= 8_00_00) { + $this->name = $name; + $this->nullable = \in_array('null', array_map('trim', explode('|', strtolower($name))), true); + } else { + $this->name = $name; + $this->nullable = false; + } + + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + } + + public function getName(): string + { + return $this->name; + } + + public function getStartIndex(): int + { + if (null === $this->startIndex) { + throw new \RuntimeException('TypeAnalysis: no start index.'); + } + + return $this->startIndex; + } + + public function getEndIndex(): int + { + if (null === $this->endIndex) { + throw new \RuntimeException('TypeAnalysis: no end index.'); + } + + return $this->endIndex; + } + + public function isReservedType(): bool + { + return \in_array(strtolower($this->name), self::RESERVED_TYPES, true); + } + + public function isNullable(): bool + { + return $this->nullable; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php new file mode 100644 index 0000000..ea700b0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Dariusz Rumiński + * @author Vladimir Reznichenko + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArgumentsAnalyzer +{ + private const ARGUMENT_INFO_SKIP_TYPES = [\T_ELLIPSIS, \T_FINAL, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; + + /** + * Count amount of parameters in a function/method reference. + */ + public function countArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): int + { + return \count($this->getArguments($tokens, $openParenthesis, $closeParenthesis)); + } + + /** + * Returns start and end token indices of arguments. + * + * Returns an array with each key being the first token of an + * argument and the value the last. Including non-function tokens + * such as comments and white space tokens, but without the separation + * tokens like '(', ',' and ')'. + * + * @return array + */ + public function getArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): array + { + $arguments = []; + $firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis); + + if ($tokens[$firstSensibleToken]->equals(')')) { + return $arguments; + } + + $paramContentIndex = $openParenthesis + 1; + $argumentsStart = $paramContentIndex; + + for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) { + $token = $tokens[$paramContentIndex]; + + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + + if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) { + $paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex); + + continue; + } + + // if comma matched, increase arguments counter + if ($token->equals(',')) { + if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) { + break; // trailing ',' in function call (PHP 7.3) + } + + $arguments[$argumentsStart] = $paramContentIndex - 1; + $argumentsStart = $paramContentIndex + 1; + } + } + + $arguments[$argumentsStart] = $paramContentIndex - 1; + + return $arguments; + } + + public function getArgumentInfo(Tokens $tokens, int $argumentStart, int $argumentEnd): ArgumentAnalysis + { + $info = [ + 'default' => null, + 'name' => null, + 'name_index' => null, + 'type' => null, + 'type_index_start' => null, + 'type_index_end' => null, + ]; + + $sawName = false; + + for ($index = $argumentStart; $index <= $argumentEnd; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $index); + + continue; + } + + if ( + $token->isComment() + || $token->isWhitespace() + || $token->isGivenKind(self::ARGUMENT_INFO_SKIP_TYPES) + || $token->equals('&') + ) { + continue; + } + + if ($token->isGivenKind(\T_VARIABLE)) { + if ($sawName) { + continue; + } + $sawName = true; + $info['name_index'] = $index; + $info['name'] = $token->getContent(); + + continue; + } + + if ($token->equals('=')) { + continue; + } + + if ($sawName) { + $info['default'] .= $token->getContent(); + } else { + $info['type_index_start'] = ($info['type_index_start'] > 0) ? $info['type_index_start'] : $index; + $info['type_index_end'] = $index; + $info['type'] .= $token->getContent(); + } + } + + if (null === $info['name']) { + $info['type'] = null; + } + + return new ArgumentAnalysis( + $info['name'], + $info['name_index'], + $info['default'], + null !== $info['type'] ? new TypeAnalysis($info['type'], $info['type_index_start'], $info['type_index_end']) : null, + ); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php new file mode 100644 index 0000000..7e7529b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php @@ -0,0 +1,210 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @phpstan-import-type _AttributeItems from AttributeAnalysis + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AttributeAnalyzer +{ + private const TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE = [ + ';', + '{', + [\T_ATTRIBUTE], + [\T_FUNCTION], + [\T_OPEN_TAG], + [\T_OPEN_TAG_WITH_ECHO], + [\T_PRIVATE], + [\T_PROTECTED], + [\T_PUBLIC], + [\T_RETURN], + [\T_VARIABLE], + [CT::T_ATTRIBUTE_CLOSE], + ]; + + /** + * Check if given index is an attribute declaration. + */ + public static function isAttribute(Tokens $tokens, int $index): bool + { + if ( + !$tokens[$index]->isGivenKind(\T_STRING) // checked token is not a string + || !$tokens->isAnyTokenKindsFound([FCT::T_ATTRIBUTE]) // no attributes in the tokens collection + ) { + return false; + } + + $attributeStartIndex = $tokens->getPrevTokenOfKind($index, self::TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE); + if (!$tokens[$attributeStartIndex]->isGivenKind(\T_ATTRIBUTE)) { + return false; + } + + // now, between attribute start and the attribute candidate index cannot be more "(" than ")" + $count = 0; + for ($i = $attributeStartIndex + 1; $i < $index; ++$i) { + if ($tokens[$i]->equals('(')) { + ++$count; + } elseif ($tokens[$i]->equals(')')) { + --$count; + } + } + + return 0 === $count; + } + + /** + * Find all consecutive elements that start with #[ and end with ] and the attributes inside. + * + * @return non-empty-list + */ + public static function collect(Tokens $tokens, int $index): array + { + if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { + throw new \InvalidArgumentException('Given index must point to an attribute.'); + } + + // Rewind to first attribute in group + while ($tokens[$prevIndex = $tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $prevIndex); + } + + $elements = []; + + $openingIndex = $index; + do { + $elements[] = $element = self::collectOne($tokens, $openingIndex); + $openingIndex = $tokens->getNextMeaningfulToken($element->getEndIndex()); + } while ($tokens[$openingIndex]->isGivenKind(\T_ATTRIBUTE)); + + return $elements; + } + + /** + * Find one element that starts with #[ and ends with ] and the attributes inside. + */ + public static function collectOne(Tokens $tokens, int $index): AttributeAnalysis + { + if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { + throw new \InvalidArgumentException('Given index must point to an attribute.'); + } + + $startIndex = $index; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + // Include comments/PHPDoc if they are present + $startIndex = $tokens->getNextNonWhitespace($prevIndex); + } + + $closingIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $endIndex = $tokens->getNextNonWhitespace($closingIndex); + + return new AttributeAnalysis( + $startIndex, + $endIndex - 1, + $index, + $closingIndex, + self::collectAttributes($tokens, $index, $closingIndex), + ); + } + + public static function determineAttributeFullyQualifiedName(Tokens $tokens, string $name, int $index): string + { + if ('\\' === $name[0]) { + return $name; + } + + if (!$tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + $index = $tokens->getNextTokenOfKind($index, [[\T_STRING], [\T_NS_SEPARATOR]]); + } + + [$namespaceAnalysis, $namespaceUseAnalyses] = NamespacesAnalyzer::collectNamespaceAnalysis($tokens, $index); + $namespace = $namespaceAnalysis->getFullName(); + $firstTokenOfName = $tokens[$index]->getContent(); + $namespaceUseAnalysis = $namespaceUseAnalyses[$firstTokenOfName] ?? false; + + if ($namespaceUseAnalysis instanceof NamespaceUseAnalysis) { + $namespace = $namespaceUseAnalysis->getFullName(); + + if ($name === $firstTokenOfName) { + return $namespace; + } + + $name = substr((string) strstr($name, '\\'), 1); + } + + return $namespace.'\\'.$name; + } + + /** + * @return _AttributeItems + */ + private static function collectAttributes(Tokens $tokens, int $index, int $closingIndex): array + { + $elements = []; + + do { + $attributeStartIndex = $index + 1; + + $nameStartIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING], [\T_NS_SEPARATOR]]); + $index = $tokens->getNextTokenOfKind($attributeStartIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); + $attributeName = $tokens->generatePartialCode($nameStartIndex, $tokens->getPrevMeaningfulToken($index)); + + // Find closing parentheses, we need to do this in case there's a comma inside the parentheses + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $index = $tokens->getNextTokenOfKind($index, [',', [CT::T_ATTRIBUTE_CLOSE]]); + } + + $elements[] = [ + 'start' => $attributeStartIndex, + 'end' => $index - 1, + 'name' => $attributeName, + ]; + + $nextIndex = $index; + + // In case there's a comma right before T_ATTRIBUTE_CLOSE + if ($nextIndex < $closingIndex) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + } + } while ($nextIndex < $closingIndex); + + // End last element at newline if it exists and there's no trailing comma + --$index; + while ($tokens[$index]->isWhitespace()) { + if (Preg::match('/\R/', $tokens[$index]->getContent())) { + $lastElementKey = array_key_last($elements); + $elements[$lastElementKey]['end'] = $index - 1; + + break; + } + --$index; + } + + return $elements; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php new file mode 100644 index 0000000..5399d19 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BlocksAnalyzer +{ + public function isBlock(Tokens $tokens, int $openIndex, int $closeIndex): bool + { + if (!$tokens->offsetExists($openIndex)) { + throw new \InvalidArgumentException(\sprintf('Tokex index %d for potential block opening does not exist.', $openIndex)); + } + + if (!$tokens->offsetExists($closeIndex)) { + throw new \InvalidArgumentException(\sprintf('Token index %d for potential block closure does not exist.', $closeIndex)); + } + + $blockType = $this->getBlockType($tokens[$openIndex]); + + if (null === $blockType) { + return false; + } + + return $closeIndex === $tokens->findBlockEnd($blockType, $openIndex); + } + + /** + * @return Tokens::BLOCK_TYPE_* + */ + private function getBlockType(Token $token): ?int + { + foreach (Tokens::getBlockEdgeDefinitions() as $blockType => $definition) { + if ($token->equals($definition['start'])) { + return $blockType; + } + } + + return null; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php new file mode 100644 index 0000000..f0d39ef --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassyAnalyzer +{ + public function isClassyInvocation(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_STRING)) { + throw new \LogicException(\sprintf('No T_STRING at given index %d, got "%s".', $index, $tokens[$index]->getName())); + } + + if ((new Analysis\TypeAnalysis($token->getContent()))->isReservedType()) { + return false; + } + + $next = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$next]; + + if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) { + return false; + } + + if ($nextToken->isGivenKind([\T_DOUBLE_COLON, \T_ELLIPSIS, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_VARIABLE])) { + return true; + } + + $prev = $tokens->getPrevMeaningfulToken($index); + + while ($tokens[$prev]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING])) { + $prev = $tokens->getPrevMeaningfulToken($prev); + } + + $prevToken = $tokens[$prev]; + + if ($prevToken->isGivenKind([\T_EXTENDS, \T_INSTANCEOF, \T_INSTEADOF, \T_IMPLEMENTS, \T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_TYPE_COLON, CT::T_USE_TRAIT])) { + return true; + } + + if (\PHP_VERSION_ID >= 8_00_00 && $nextToken->equals(')') && $prevToken->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($prev)]->isGivenKind(\T_CATCH)) { + return true; + } + + if (AttributeAnalyzer::isAttribute($tokens, $index)) { + return true; + } + + // `Foo & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = Foo & $bar; + if ($nextToken->equals('&') && $tokens[$tokens->getNextMeaningfulToken($next)]->isGivenKind(\T_VARIABLE)) { + $checkIndex = $tokens->getPrevTokenOfKind($prev + 1, [';', '{', '}', [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]]); + + return $tokens[$checkIndex]->isGivenKind(\T_FUNCTION); + } + + if (!$prevToken->equals(',')) { + return false; + } + + do { + $prev = $tokens->getPrevMeaningfulToken($prev); + } while ($tokens[$prev]->equalsAny([',', [\T_NS_SEPARATOR], [\T_STRING], [CT::T_NAMESPACE_OPERATOR]])); + + return $tokens[$prev]->isGivenKind([\T_IMPLEMENTS, CT::T_USE_TRAIT]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php new file mode 100644 index 0000000..1103ae8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php @@ -0,0 +1,365 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CommentsAnalyzer +{ + private const TYPE_HASH = 1; + private const TYPE_DOUBLE_SLASH = 2; + private const TYPE_SLASH_ASTERISK = 3; + private const SKIP_TYPES = [ + \T_PRIVATE, + \T_PROTECTED, + \T_PUBLIC, + \T_VAR, + \T_FUNCTION, + \T_FN, + \T_ABSTRACT, + \T_CONST, + \T_NAMESPACE, + \T_REQUIRE, + \T_REQUIRE_ONCE, + \T_INCLUDE, + \T_INCLUDE_ONCE, + \T_FINAL, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + FCT::T_READONLY, + FCT::T_PUBLIC_SET, + FCT::T_PROTECTED_SET, + FCT::T_PRIVATE_SET, + ]; + + public function isHeaderComment(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + if (null === $tokens->getNextMeaningfulToken($index)) { + return false; + } + + $prevIndex = $tokens->getPrevNonWhitespace($index); + + if ($tokens[$prevIndex]->equals(';')) { + $braceCloseIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$braceCloseIndex]->equals(')')) { + return false; + } + + $braceOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $braceCloseIndex); + $declareIndex = $tokens->getPrevMeaningfulToken($braceOpenIndex); + if (!$tokens[$declareIndex]->isGivenKind(\T_DECLARE)) { + return false; + } + + $prevIndex = $tokens->getPrevNonWhitespace($declareIndex); + } + + return $tokens[$prevIndex]->isGivenKind(\T_OPEN_TAG); + } + + /** + * Check if comment at given index precedes structural element. + * + * @see https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + public function isBeforeStructuralElement(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if (!$token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + $nextIndex = $this->getNextTokenIndex($tokens, $index); + + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + return false; + } + + if ($this->isStructuralElement($tokens, $nextIndex)) { + return true; + } + + if ($this->isValidControl($tokens, $token, $nextIndex)) { + return true; + } + + if ($this->isValidVariable($tokens, $nextIndex)) { + return true; + } + + if ($this->isValidVariableAssignment($tokens, $token, $nextIndex)) { + return true; + } + + if ($tokens[$nextIndex]->isGivenKind(CT::T_USE_TRAIT)) { + return true; + } + + return false; + } + + /** + * Check if comment at given index precedes return statement. + */ + public function isBeforeReturn(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + $nextIndex = $this->getNextTokenIndex($tokens, $index); + + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + return false; + } + + return $tokens[$nextIndex]->isGivenKind(\T_RETURN); + } + + /** + * Return array of indices that are part of a comment started at given index. + * + * @param int $index T_COMMENT index + * + * @return non-empty-list + */ + public function getCommentBlockIndices(Tokens $tokens, int $index): array + { + if (!$tokens[$index]->isGivenKind(\T_COMMENT)) { + throw new \InvalidArgumentException('Given index must point to a comment.'); + } + + $commentType = $this->getCommentType($tokens[$index]->getContent()); + $indices = [$index]; + + if (self::TYPE_SLASH_ASTERISK === $commentType) { + return $indices; + } + + $count = \count($tokens); + ++$index; + + for (; $index < $count; ++$index) { + if ($tokens[$index]->isComment()) { + if ($commentType === $this->getCommentType($tokens[$index]->getContent())) { + $indices[] = $index; + + continue; + } + + break; + } + + if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { + break; + } + } + + return $indices; + } + + /** + * @see https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + private function isStructuralElement(Tokens $tokens, int $index): bool + { + $token = $tokens[$index]; + + if ($token->isClassy() || $token->isGivenKind(self::SKIP_TYPES)) { + return true; + } + + if ($token->isGivenKind(\T_STRING)) { + $content = strtolower($token->getContent()); + + return 'get' === $content || 'set' === $content; + } + + if ($token->isGivenKind(\T_CASE)) { + $enumParent = $tokens->getPrevTokenOfKind($index, [[FCT::T_ENUM], [\T_SWITCH]]); + + return $tokens[$enumParent]->isGivenKind(FCT::T_ENUM); + } + + if ($token->isGivenKind(\T_STATIC)) { + return !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON); + } + + return false; + } + + /** + * Checks control structures (for, foreach, if, switch, while) for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $controlIndex index of control structure Token + */ + private function isValidControl(Tokens $tokens, Token $docsToken, int $controlIndex): bool + { + if (!$tokens[$controlIndex]->isGivenKind([ + \T_FOR, + \T_FOREACH, + \T_IF, + \T_SWITCH, + \T_WHILE, + ])) { + return false; + } + + $openParenthesisIndex = $tokens->getNextMeaningfulToken($controlIndex); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + $docsContent = $docsToken->getContent(); + + for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { + $token = $tokens[$index]; + + if ( + $token->isGivenKind(\T_VARIABLE) + && str_contains($docsContent, $token->getContent()) + ) { + return true; + } + } + + return false; + } + + /** + * Checks variable assignments through `list()`, `print()` etc. calls for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $languageConstructIndex index of variable Token + */ + private function isValidVariableAssignment(Tokens $tokens, Token $docsToken, int $languageConstructIndex): bool + { + if (!$tokens[$languageConstructIndex]->isGivenKind([ + \T_LIST, + \T_PRINT, + \T_ECHO, + CT::T_DESTRUCTURING_BRACKET_OPEN, + ])) { + return false; + } + + $endKind = $tokens[$languageConstructIndex]->isGivenKind(CT::T_DESTRUCTURING_BRACKET_OPEN) + ? [CT::T_DESTRUCTURING_BRACKET_CLOSE] + : ')'; + + $endIndex = $tokens->getNextTokenOfKind($languageConstructIndex, [$endKind]); + + $docsContent = $docsToken->getContent(); + + for ($index = $languageConstructIndex + 1; $index < $endIndex; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_VARIABLE) && str_contains($docsContent, $token->getContent())) { + return true; + } + } + + return false; + } + + /** + * Checks variable assignments for correct docblock usage. + * + * @param int $index index of variable Token + */ + private function isValidVariable(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + return false; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + return $tokens[$nextIndex]->equalsAny([ + '=', + // arithmetic assignments + [\T_PLUS_EQUAL, '+='], + [\T_MINUS_EQUAL, '-='], + [\T_MUL_EQUAL, '*='], + [\T_DIV_EQUAL, '/='], + [\T_MOD_EQUAL, '%='], + [\T_POW_EQUAL, '**='], + // bitwise assignments + [\T_AND_EQUAL, '&='], + [\T_OR_EQUAL, '|='], + [\T_XOR_EQUAL, '^='], + [\T_SL_EQUAL, '<<='], + [\T_SR_EQUAL, '>>='], + // other assignments + [\T_COALESCE_EQUAL, '??='], + [\T_CONCAT_EQUAL, '.='], + ]); + } + + private function getCommentType(string $content): int + { + if (str_starts_with($content, '#')) { + return self::TYPE_HASH; + } + + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + + return self::TYPE_DOUBLE_SLASH; + } + + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd): int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent()); + } + + return $lineCount; + } + + private function getNextTokenIndex(Tokens $tokens, int $startIndex): ?int + { + $nextIndex = $startIndex; + + do { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + while (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + } while (null !== $nextIndex && $tokens[$nextIndex]->equals('(')); + + return $nextIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php new file mode 100644 index 0000000..b2bede9 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php @@ -0,0 +1,318 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + * + * @TODO 4.0: mark @internal + */ +final class ControlCaseStructuresAnalyzer +{ + private const SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT = [ + \T_SWITCH, + FCT::T_MATCH, + FCT::T_ENUM, + ]; + + /** + * @param list $types Token types of interest of which analyses must be returned + * + * @return iterable + */ + public static function findControlStructures(Tokens $tokens, array $types): iterable + { + if (\count($types) < 1) { + return; // quick skip + } + + foreach ($types as $type) { + if (!\in_array($type, self::SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT, true)) { + throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $type)); + } + } + + if (!$tokens->isAnyTokenKindsFound($types)) { + return; // quick skip + } + + $depth = -1; + + /** + * @var list, + * default: null|array{index: int, open: int}, + * alternative_syntax: bool, + * open?: int, + * end?: int, + * }> $stack + */ + $stack = []; + $isTypeOfInterest = false; + + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(self::SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT)) { + ++$depth; + + $stack[$depth] = [ + 'kind' => $token->getId(), + 'index' => $index, + 'brace_count' => 0, + 'cases' => [], + 'default' => null, + 'alternative_syntax' => false, + ]; + + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + + if ($token->isGivenKind(\T_SWITCH)) { + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + $stack[$depth]['alternative_syntax'] = $tokens[$stack[$depth]['open']]->equals(':'); + } elseif ($token->isGivenKind(FCT::T_MATCH)) { + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + } elseif ($token->isGivenKind(FCT::T_ENUM)) { + $stack[$depth]['open'] = $tokens->getNextTokenOfKind($index, ['{']); + } + + continue; + } + + if ($depth < 0) { + continue; + } + + \assert(isset($stack[$depth])); + + if ($token->equals('{')) { + ++$stack[$depth]['brace_count']; + + continue; + } + + if ($token->equals('}')) { + --$stack[$depth]['brace_count']; + + if (0 === $stack[$depth]['brace_count']) { + if ($stack[$depth]['alternative_syntax']) { + continue; + } + + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + + \assert(isset($stack[$depth]['open'])); + + yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); + } + + array_pop($stack); + --$depth; + + if ($depth < -1) { // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure.'); + } + + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + } + } + + continue; + } + + if ($tokens[$index]->isGivenKind(\T_ENDSWITCH)) { + if (!$stack[$depth]['alternative_syntax']) { + throw new \RuntimeException('Analysis syntax failure, unexpected "T_ENDSWITCH".'); + } + + if (\T_SWITCH !== $stack[$depth]['kind']) { + throw new \RuntimeException('Analysis type failure, unexpected "T_ENDSWITCH".'); + } + + if (0 !== $stack[$depth]['brace_count']) { + throw new \RuntimeException('Analysis count failure, unexpected "T_ENDSWITCH".'); + } + + $index = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + + \assert(isset($stack[$depth]['open'])); + + yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); + } + + array_pop($stack); + --$depth; + + if ($depth < -1) { // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure ("T_ENDSWITCH").'); + } + + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); + } + } + + if (!$isTypeOfInterest) { + continue; // don't bother to analyse stuff that caller is not interested in + } + + if ($token->isGivenKind(\T_CASE)) { + \assert(isset($stack[$depth]['kind'])); + + $stack[$depth]['cases'][] = ['index' => $index, 'open' => self::findCaseOpen($tokens, $stack[$depth]['kind'], $index)]; + } elseif ($token->isGivenKind(\T_DEFAULT)) { + \assert(isset($stack[$depth]['kind'])); + + if (null !== $stack[$depth]['default']) { + throw new \RuntimeException('Analysis multiple "default" found.'); + } + + $stack[$depth]['default'] = ['index' => $index, 'open' => self::findDefaultOpen($tokens, $stack[$depth]['kind'], $index)]; + } + } + } + + /** + * @param array{ + * kind: int, + * index: int, + * brace_count: int, + * cases: list, + * default: null|array{index: int, open: int}, + * alternative_syntax: bool, + * open: int, + * end: int, + * } $analysis + */ + private static function buildControlCaseStructureAnalysis(array $analysis): AbstractControlCaseStructuresAnalysis + { + $default = null === $analysis['default'] + ? null + : new DefaultAnalysis($analysis['default']['index'], $analysis['default']['open']); + + $cases = []; + + foreach ($analysis['cases'] as $case) { + $cases[$case['index']] = new CaseAnalysis($case['index'], $case['open']); + } + + sort($cases); + + if (\T_SWITCH === $analysis['kind']) { + return new SwitchAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $cases, + $default, + ); + } + + if (FCT::T_ENUM === $analysis['kind']) { + return new EnumAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $cases, + ); + } + + if (FCT::T_MATCH === $analysis['kind']) { + return new MatchAnalysis( + $analysis['index'], + $analysis['open'], + $analysis['end'], + $default, + ); + } + + throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $analysis['kind'])); + } + + private static function findCaseOpen(Tokens $tokens, int $kind, int $index): int + { + if (\T_SWITCH === $kind) { + $ternariesCount = 0; + + --$index; + while (true) { + ++$index; + + if ($tokens[$index]->equalsAny(['(', '{'])) { // skip constructs + $type = Tokens::detectBlockType($tokens[$index]); + $index = $tokens->findBlockEnd($type['type'], $index); + + continue; + } + + if ($tokens[$index]->equals('?')) { + ++$ternariesCount; + + continue; + } + + if ($tokens[$index]->equalsAny([':', ';'])) { + if (0 === $ternariesCount) { + break; + } + + --$ternariesCount; + } + } + + return $index; + } + + if (FCT::T_ENUM === $kind) { + return $tokens->getNextTokenOfKind($index, ['=', ';']); + } + + throw new \InvalidArgumentException(\sprintf('Unexpected case for type "%d".', $kind)); + } + + private static function findDefaultOpen(Tokens $tokens, int $kind, int $index): int + { + if (\T_SWITCH === $kind) { + return $tokens->getNextTokenOfKind($index, [':', ';']); + } + + if (FCT::T_MATCH === $kind) { + return $tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); + } + + throw new \InvalidArgumentException(\sprintf('Unexpected default for type "%d".', $kind)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php new file mode 100644 index 0000000..519f4c1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php @@ -0,0 +1,173 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + * + * @phpstan-import-type _AttributeItem from \PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DataProviderAnalyzer +{ + private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER + .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; + + /** + * @return list + */ + public function getDataProviders(Tokens $tokens, int $startIndex, int $endIndex): array + { + $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); + + $methods = $this->getMethods($tokens, $startIndex, $endIndex); + + $dataProviders = []; + foreach ($methods as $methodIndex) { + [$attributeIndex, $docCommentIndex] = $this->getAttributeIndexAndDocCommentIndices($tokens, $methodIndex); + + if (null !== $attributeIndex) { + foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) { + foreach ($attributeAnalysis->getAttributes() as $attribute) { + $dataProviderNameIndex = $this->getDataProviderNameIndex($tokens, $fullyQualifiedNameAnalyzer, $attribute); + if (null === $dataProviderNameIndex) { + continue; + } + $dataProviders[substr($tokens[$dataProviderNameIndex]->getContent(), 1, -1)][] = [$dataProviderNameIndex, 0]; + } + } + } + + if (null !== $docCommentIndex) { + Preg::matchAll( + '/@dataProvider\h+(('.self::REGEX_CLASS.'::)?'.TypeExpression::REGEX_IDENTIFIER.')/', + $tokens[$docCommentIndex]->getContent(), + $matches, + \PREG_OFFSET_CAPTURE, + ); + + foreach ($matches[1] as $k => [$matchName]) { + \assert(isset($matches[0][$k])); + + $dataProviders[$matchName][] = [$docCommentIndex, $matches[0][$k][1]]; + } + } + } + + $dataProviderAnalyses = []; + foreach ($dataProviders as $dataProviderName => $dataProviderUsages) { + $lowercaseDataProviderName = strtolower($dataProviderName); + if (!\array_key_exists($lowercaseDataProviderName, $methods)) { + continue; + } + $dataProviderAnalyses[$methods[$lowercaseDataProviderName]] = new DataProviderAnalysis( + $tokens[$methods[$lowercaseDataProviderName]]->getContent(), + $methods[$lowercaseDataProviderName], + $dataProviderUsages, + ); + } + + ksort($dataProviderAnalyses); + + return array_values($dataProviderAnalyses); + } + + /** + * @return array + */ + private function getMethods(Tokens $tokens, int $startIndex, int $endIndex): array + { + $functions = []; + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $functionNameIndex = $tokens->getNextNonWhitespace($index); + + if (!$tokens[$functionNameIndex]->isGivenKind(\T_STRING)) { + continue; + } + + $functions[strtolower($tokens[$functionNameIndex]->getContent())] = $functionNameIndex; + } + + return $functions; + } + + /** + * @return array{null|int, null|int} + */ + private function getAttributeIndexAndDocCommentIndices(Tokens $tokens, int $index): array + { + $attributeIndex = null; + $docCommentIndex = null; + while (!$tokens[$index]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) { + --$index; + + if ($tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { + $attributeIndex = $index; + } elseif ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + $docCommentIndex = $index; + } + } + + return [$attributeIndex, $docCommentIndex]; + } + + /** + * @param _AttributeItem $attribute + */ + private function getDataProviderNameIndex(Tokens $tokens, FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, array $attribute): ?int + { + $fullyQualifiedName = $fullyQualifiedNameAnalyzer->getFullyQualifiedName( + $attribute['name'], + $tokens->getNextMeaningfulToken($attribute['start']), + NamespaceUseAnalysis::TYPE_CLASS, + ); + + // note: do not apply `DataProvider::class` here, as it would confuse `composer-dependency-analyser` to have PHPUnit as non-dev dependency + if ('PHPUnit\Framework\Attributes\DataProvider' !== $fullyQualifiedName) { + return null; + } + + $closeParenthesisIndex = $tokens->getPrevTokenOfKind($attribute['end'] + 1, [')', [\T_ATTRIBUTE]]); + if ($tokens[$closeParenthesisIndex]->isGivenKind(\T_ATTRIBUTE)) { + return null; + } + + $dataProviderNameIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + if (!$tokens[$dataProviderNameIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + return null; + } + + $openParenthesisIndex = $tokens->getPrevMeaningfulToken($dataProviderNameIndex); + if (!$tokens[$openParenthesisIndex]->equals('(')) { + return null; + } + + return $dataProviderNameIndex; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FixerAnnotationAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FixerAnnotationAnalyzer.php new file mode 100644 index 0000000..d9f5c37 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FixerAnnotationAnalyzer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Extracts @php-cs-fixer-* annotations from the given Tokens collection. + * + * Those annotations are controlling low-level PHP CS Fixer internal + * are looked for only at the top and at the bottom of the file. + * Any syntax of comment is allowed. + * + * @internal + * + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FixerAnnotationAnalyzer +{ + /** + * @return array> + */ + public function find(Tokens $tokens): array + { + $comments = []; + $annotations = []; + + $count = $tokens->count(); + $index = 0; + + for (0; $index < $count; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind([ + \T_OPEN_TAG, + \T_OPEN_TAG_WITH_ECHO, + \T_WHITESPACE, + ]) || $token->equals(';')) { + continue; + } + + if ($token->isGivenKind(\T_DECLARE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextIndex); + + continue; + } + + if ($token->isComment()) { + $comments[] = $token->getContent(); + + continue; + } + + break; + } + + for ($indexBackwards = $count - 1; $indexBackwards > $index; --$indexBackwards) { + $token = $tokens[$indexBackwards]; + + if ($token->isGivenKind([ + \T_CLOSE_TAG, + \T_WHITESPACE, + ]) || $token->equals(';')) { + continue; + } + + if ($token->isComment()) { + $comments[] = $token->getContent(); + + continue; + } + + break; + } + + Preg::matchAll( + '/^\h*[*\/]+\h+@(php-cs-fixer-\w+\h+(?:@?[\w\/,])+)/m', + implode("\n", $comments), + $matches, + ); + + foreach ($matches[1] as $match) { + $matchParts = explode(' ', $match, 2); + \assert(2 === \count($matchParts)); + + $annotations[$matchParts[0]] ??= []; + array_push($annotations[$matchParts[0]], ...explode(',', $matchParts[1])); + } + + foreach ($annotations as $annotation => $vals) { + $duplicates = array_keys( + array_filter( + array_count_values($vals), + static fn (int $c): bool => $c > 1, + ), + ); + + if (0 !== \count($duplicates)) { + throw new \RuntimeException(\sprintf('Duplicated values found for annotation "@%s": "%s".', $annotation, implode('", "', $duplicates))); + } + + sort($vals); + $annotations[$annotation] = $vals; + } + + return $annotations; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FullyQualifiedNameAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FullyQualifiedNameAnalyzer.php new file mode 100644 index 0000000..530a1d8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FullyQualifiedNameAnalyzer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FullyQualifiedNameAnalyzer +{ + private Tokens $tokens; + + /** + * @var list + */ + private array $namespaceAnalyses = []; + + /** + * @var array> + */ + private array $namespaceUseAnalyses = []; + + public function __construct(Tokens $tokens) + { + $this->tokens = $tokens; + } + + /** + * @param NamespaceUseAnalysis::TYPE_* $importType + */ + public function getFullyQualifiedName(string $name, int $indexInNamespace, int $importType): string + { + return ltrim($this->getFullyQualifiedNameWithPossiblyLeadingSlash($name, $indexInNamespace, $importType), '\\'); + } + + /** + * @param NamespaceUseAnalysis::TYPE_* $importType + */ + private function getFullyQualifiedNameWithPossiblyLeadingSlash(string $name, int $indexInNamespace, int $importType): string + { + if ('\\' === $name[0]) { + return $name; + } + + $namespaceAnalysis = $this->getNamespaceAnalysis($indexInNamespace); + + $this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()] ??= (new NamespaceUsesAnalyzer())->getDeclarationsInNamespace($this->tokens, $namespaceAnalysis); + \assert(isset($this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()])); + + $declarations = []; + foreach ($this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()] as $namespaceUseAnalysis) { + if ($namespaceUseAnalysis->getType() !== $importType) { + continue; + } + $declarations[strtolower($namespaceUseAnalysis->getShortName())] = $namespaceUseAnalysis->getFullName(); + } + + $lowercaseName = strtolower($name); + foreach ($declarations as $lowercaseShortName => $fullName) { + if ($lowercaseName === $lowercaseShortName) { + return $fullName; + } + + if (!str_starts_with($lowercaseName, $lowercaseShortName.'\\')) { + continue; + } + + return $fullName.substr($name, \strlen($lowercaseShortName)); + } + + return $namespaceAnalysis->getFullName().'\\'.$name; + } + + private function getNamespaceAnalysis(int $index): NamespaceAnalysis + { + foreach ($this->namespaceAnalyses as $namespace) { + if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { + return $namespace; + } + } + + $namespace = (new NamespacesAnalyzer())->getNamespaceAt($this->tokens, $index); + + $this->namespaceAnalyses[] = $namespace; + + return $namespace; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php new file mode 100644 index 0000000..54d7bd5 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php @@ -0,0 +1,288 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FunctionsAnalyzer +{ + private const POSSIBLE_KINDS = [ + \T_DOUBLE_COLON, \T_FUNCTION, CT::T_NAMESPACE_OPERATOR, \T_NEW, CT::T_RETURN_REF, \T_STRING, \T_OBJECT_OPERATOR, FCT::T_NULLSAFE_OBJECT_OPERATOR, FCT::T_ATTRIBUTE]; + + /** + * @var array{tokens: string, imports: list, declarations: list} + */ + private array $functionsAnalysis = ['tokens' => '', 'imports' => [], 'declarations' => []]; + + public function isGlobalFunctionCall(Tokens $tokens, int $index): bool + { + return $this->isGlobalFunctionCallOrUsage($tokens, $index, true); + } + + public function isGlobalFunctionUsage(Tokens $tokens, int $index): bool + { + return $this->isGlobalFunctionCallOrUsage($tokens, $index, false); + } + + /** + * @return array + */ + public function getFunctionArguments(Tokens $tokens, int $functionIndex): array + { + $argumentsStart = $tokens->getNextTokenOfKind($functionIndex, ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $argumentsStart); + $argumentAnalyzer = new ArgumentsAnalyzer(); + $arguments = []; + + foreach ($argumentAnalyzer->getArguments($tokens, $argumentsStart, $argumentsEnd) as $start => $end) { + $argumentInfo = $argumentAnalyzer->getArgumentInfo($tokens, $start, $end); + $arguments[$argumentInfo->getName()] = $argumentInfo; + } + + return $arguments; + } + + public function getFunctionReturnType(Tokens $tokens, int $methodIndex): ?TypeAnalysis + { + $argumentsStart = $tokens->getNextTokenOfKind($methodIndex, ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $argumentsStart); + $typeColonIndex = $tokens->getNextMeaningfulToken($argumentsEnd); + + if (!$tokens[$typeColonIndex]->isGivenKind(CT::T_TYPE_COLON)) { + return null; + } + + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($typeColonIndex); + $typeEndIndex = $typeStartIndex; + $functionBodyStart = $tokens->getNextTokenOfKind($typeColonIndex, ['{', ';', [\T_DOUBLE_ARROW]]); + + for ($i = $typeStartIndex; $i < $functionBodyStart; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + + return new TypeAnalysis($type, $typeStartIndex, $typeEndIndex); + } + + public function isTheSameClassCall(Tokens $tokens, int $index): bool + { + if (!$tokens->offsetExists($index)) { + throw new \InvalidArgumentException(\sprintf('Token index %d does not exist.', $index)); + } + + $operatorIndex = $tokens->getPrevMeaningfulToken($index); + + if (null === $operatorIndex) { + return false; + } + + if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(\T_DOUBLE_COLON)) { + return false; + } + + $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); + + if (null === $referenceIndex) { + return false; + } + + if (!$tokens[$referenceIndex]->equalsAny([[\T_VARIABLE, '$this'], [\T_STRING, 'self'], [\T_STATIC, 'static']], false)) { + return false; + } + + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + + /** + * Important: risky because of the limited (file) scope of the tool. + */ + private function isGlobalFunctionCallOrUsage(Tokens $tokens, int $index, bool $callOnly): bool + { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + return false; + } + + $openParenthesisIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$openParenthesisIndex]->equals('(')) { + return false; + } + + $previousIsNamespaceSeparator = false; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $previousIsNamespaceSeparator = true; + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + + if ($tokens[$prevIndex]->isGivenKind(self::POSSIBLE_KINDS)) { + return false; + } + + if ($callOnly && $tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + return false; + } + + if ($previousIsNamespaceSeparator) { + return true; + } + + $functionName = strtolower($tokens[$index]->getContent()); + + if ('set' === $functionName) { + if (!$tokens[$prevIndex]->equalsAny([[CT::T_PROPERTY_HOOK_BRACE_OPEN], ';', '}'])) { + return true; + } + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); + if ($tokens[$afterCloseParenthesisIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]])) { + return false; + } + } + + if ($tokens->isChanged() || $tokens->getCodeHash() !== $this->functionsAnalysis['tokens']) { + $this->buildFunctionsAnalysis($tokens); + } + + // figure out in which namespace we are + $scopeStartIndex = 0; + $scopeEndIndex = \count($tokens) - 1; + $inGlobalNamespace = false; + + foreach ($tokens->getNamespaceDeclarations() as $declaration) { + $scopeStartIndex = $declaration->getScopeStartIndex(); + $scopeEndIndex = $declaration->getScopeEndIndex(); + + if ($index >= $scopeStartIndex && $index <= $scopeEndIndex) { + $inGlobalNamespace = $declaration->isGlobalNamespace(); + + break; + } + } + + // check if the call is to a function declared in the same namespace as the call is done, + // if the call is already in the global namespace than declared functions are in the same + // global namespace and don't need checking + + if (!$inGlobalNamespace) { + foreach ($this->functionsAnalysis['declarations'] as $functionNameIndex) { + if ($functionNameIndex < $scopeStartIndex || $functionNameIndex > $scopeEndIndex) { + continue; + } + + if (strtolower($tokens[$functionNameIndex]->getContent()) === $functionName) { + return false; + } + } + } + + foreach ($this->functionsAnalysis['imports'] as $functionUse) { + if ($functionUse->getStartIndex() < $scopeStartIndex || $functionUse->getEndIndex() > $scopeEndIndex) { + continue; + } + + if ($functionName !== strtolower($functionUse->getShortName())) { + continue; + } + + // global import like `use function \str_repeat;` + return $functionUse->getShortName() === ltrim($functionUse->getFullName(), '\\'); + } + + if (AttributeAnalyzer::isAttribute($tokens, $index)) { + return false; + } + + return true; + } + + private function buildFunctionsAnalysis(Tokens $tokens): void + { + $this->functionsAnalysis = [ + 'tokens' => $tokens->getCodeHash(), + 'imports' => [], + 'declarations' => [], + ]; + + // find declarations + + if ($tokens->isTokenKindFound(\T_FUNCTION)) { + $end = \count($tokens); + + for ($i = 0; $i < $end; ++$i) { + // skip classy, we are looking for functions not methods + if ($tokens[$i]->isGivenKind(Token::getClassyTokenKinds())) { + $i = $tokens->getNextTokenOfKind($i, ['(', '{']); + + if ($tokens[$i]->equals('(')) { // anonymous class + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $i); + $i = $tokens->getNextTokenOfKind($i, ['{']); + } + + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $i); + + continue; + } + + if (!$tokens[$i]->isGivenKind(\T_FUNCTION)) { + continue; + } + + $i = $tokens->getNextMeaningfulToken($i); + + if ($tokens[$i]->isGivenKind(CT::T_RETURN_REF)) { + $i = $tokens->getNextMeaningfulToken($i); + } + + if (!$tokens[$i]->isGivenKind(\T_STRING)) { + continue; + } + + $this->functionsAnalysis['declarations'][] = $i; + } + } + + // find imported functions + + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + + if ($tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + $declarations = $namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens); + + foreach ($declarations as $declaration) { + if ($declaration->isFunction()) { + $this->functionsAnalysis['imports'][] = $declaration; + } + } + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php new file mode 100644 index 0000000..70ed56a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class GotoLabelAnalyzer +{ + public function belongsToGoToLabel(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_STRING)) { + return false; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + + return $tokens[$prevMeaningfulTokenIndex]->equalsAny([':', ';', '{', '}', [\T_OPEN_TAG]]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php new file mode 100644 index 0000000..bdefa5b --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; + +/** + * @author VeeWee + * @author Greg Korba + * + * @internal + * + * @TODO Drop `allowMultiUses` opt-in flag when all fixers are updated and can handle multi-use statements. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamespaceUsesAnalyzer +{ + /** + * @return list + */ + public function getDeclarationsFromTokens(Tokens $tokens, bool $allowMultiUses = false): array + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + $useIndices = $tokenAnalyzer->getImportUseIndexes(); + + return $this->getDeclarations($tokens, $useIndices, $allowMultiUses); + } + + /** + * @return list + */ + public function getDeclarationsInNamespace(Tokens $tokens, NamespaceAnalysis $namespace, bool $allowMultiUses = false): array + { + $namespaceUses = []; + + foreach ($this->getDeclarationsFromTokens($tokens, $allowMultiUses) as $namespaceUse) { + if ($namespaceUse->getStartIndex() >= $namespace->getScopeStartIndex() && $namespaceUse->getStartIndex() <= $namespace->getScopeEndIndex()) { + $namespaceUses[] = $namespaceUse; + } + } + + return $namespaceUses; + } + + /** + * @param list $useIndices + * + * @return list + */ + private function getDeclarations(Tokens $tokens, array $useIndices, bool $allowMultiUses = false): array + { + $uses = []; + + foreach ($useIndices as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + + $declarations = $this->parseDeclarations($index, $endIndex, $tokens); + if (false === $allowMultiUses) { + $declarations = array_filter($declarations, static fn (NamespaceUseAnalysis $declaration) => !$declaration->isInMulti()); + } + + if ([] !== $declarations) { + $uses = array_merge($uses, $declarations); + } + } + + return $uses; + } + + /** + * @return list + */ + private function parseDeclarations(int $startIndex, int $endIndex, Tokens $tokens): array + { + $type = $this->determineImportType($tokens, $startIndex); + $potentialMulti = $tokens->getNextTokenOfKind($startIndex, [',', [CT::T_GROUP_IMPORT_BRACE_OPEN]]); + $multi = null !== $potentialMulti && $potentialMulti < $endIndex; + $index = $tokens->getNextTokenOfKind($startIndex, [[\T_STRING], [\T_NS_SEPARATOR]]); + $imports = []; + + while (null !== $index && $index <= $endIndex) { + $qualifiedName = $this->getNearestQualifiedName($tokens, $index); + $token = $tokens[$qualifiedName['afterIndex']]; + + if ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $groupStart = $groupIndex = $qualifiedName['afterIndex']; + $groupEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupStart); + + while ($groupIndex < $groupEnd) { + $chunkStart = $tokens->getNextMeaningfulToken($groupIndex); + + // Finish parsing on trailing comma (no more chunks there) + if ($tokens[$chunkStart]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + break; + } + + $groupQualifiedName = $this->getNearestQualifiedName($tokens, $chunkStart); + \assert('' !== $groupQualifiedName['fullName']); + \assert('' !== $groupQualifiedName['shortName']); + $imports[] = new NamespaceUseAnalysis( + $type, + $qualifiedName['fullName'].$groupQualifiedName['fullName'], + $groupQualifiedName['shortName'], + $groupQualifiedName['aliased'], + true, + $startIndex, + $endIndex, + $chunkStart, + $tokens->getPrevMeaningfulToken($groupQualifiedName['afterIndex']), + ); + + $groupIndex = $groupQualifiedName['afterIndex']; + } + + $index = $groupIndex; + } elseif ($token->equalsAny([',', ';', [\T_CLOSE_TAG]])) { + $previousToken = $tokens->getPrevMeaningfulToken($qualifiedName['afterIndex']); + + if (!$tokens[$previousToken]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + \assert('' !== $qualifiedName['fullName']); + \assert('' !== $qualifiedName['shortName']); + $imports[] = new NamespaceUseAnalysis( + $type, + $qualifiedName['fullName'], + $qualifiedName['shortName'], + $qualifiedName['aliased'], + $multi, + $startIndex, + $endIndex, + $multi ? $index : null, + $multi ? $previousToken : null, + ); + } + + $index = $qualifiedName['afterIndex']; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return $imports; + } + + /** + * @return NamespaceUseAnalysis::TYPE_* + */ + private function determineImportType(Tokens $tokens, int $startIndex): int + { + $potentialType = $tokens[$tokens->getNextMeaningfulToken($startIndex)]; + + if ($potentialType->isGivenKind(CT::T_FUNCTION_IMPORT)) { + return NamespaceUseAnalysis::TYPE_FUNCTION; + } + + if ($potentialType->isGivenKind(CT::T_CONST_IMPORT)) { + return NamespaceUseAnalysis::TYPE_CONSTANT; + } + + return NamespaceUseAnalysis::TYPE_CLASS; + } + + /** + * @return array{fullName: string, shortName: string, aliased: bool, afterIndex: int} + */ + private function getNearestQualifiedName(Tokens $tokens, int $index): array + { + $fullName = $shortName = ''; + $aliased = false; + + while (null !== $index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_STRING)) { + $shortName = $token->getContent(); + if (!$aliased) { + $fullName .= $shortName; + } + } elseif ($token->isGivenKind(\T_NS_SEPARATOR)) { + $fullName .= $token->getContent(); + } elseif ($token->isGivenKind(\T_AS)) { + $aliased = true; + } elseif ($token->equalsAny([ + ',', + ';', + [CT::T_GROUP_IMPORT_BRACE_OPEN], + [CT::T_GROUP_IMPORT_BRACE_CLOSE], + [\T_CLOSE_TAG], + ])) { + break; + } + + $index = $tokens->getNextMeaningfulToken($index); + } + + return [ + 'fullName' => $fullName, + 'shortName' => $shortName, + 'aliased' => $aliased, + 'afterIndex' => $index, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php new file mode 100644 index 0000000..7247413 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamespacesAnalyzer +{ + /** + * @return list + */ + public function getDeclarations(Tokens $tokens): array + { + $namespaces = []; + + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_NAMESPACE)) { + continue; + } + + $declarationEndIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + $namespace = trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)); + $declarationParts = explode('\\', $namespace); + $shortName = end($declarationParts); + + if ($tokens[$declarationEndIndex]->equals('{')) { + $scopeEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $declarationEndIndex); + } else { + $scopeEndIndex = $tokens->getNextTokenOfKind($declarationEndIndex, [[\T_NAMESPACE]]); + if (null === $scopeEndIndex) { + $scopeEndIndex = \count($tokens); + } + --$scopeEndIndex; + } + + $namespaces[] = new NamespaceAnalysis( + $namespace, + $shortName, + $index, + $declarationEndIndex, + $index, + $scopeEndIndex, + ); + + // Continue the analysis after the end of this namespace to find the next one + $index = $scopeEndIndex; + } + + if (0 === \count($namespaces) && $tokens->isTokenKindFound(\T_OPEN_TAG)) { + $namespaces[] = new NamespaceAnalysis( + '', + '', + $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0, + $openTagIndex, + $openTagIndex, + \count($tokens) - 1, + ); + } + + return $namespaces; + } + + public function getNamespaceAt(Tokens $tokens, int $index): NamespaceAnalysis + { + if (!$tokens->offsetExists($index)) { + throw new \InvalidArgumentException(\sprintf('Token index %d does not exist.', $index)); + } + + foreach ($this->getDeclarations($tokens) as $namespace) { + if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { + return $namespace; + } + } + + throw new \LogicException(\sprintf('Unable to get the namespace at index %d.', $index)); + } + + /** + * @return array{NamespaceAnalysis, array} + */ + public static function collectNamespaceAnalysis(Tokens $tokens, int $startIndex): array + { + $namespaceAnalysis = (new self())->getNamespaceAt($tokens, $startIndex); + $namespaceUseAnalyses = (new NamespaceUsesAnalyzer())->getDeclarationsInNamespace($tokens, $namespaceAnalysis); + + $uses = []; + foreach ($namespaceUseAnalyses as $use) { + if (!$use->isClass()) { + continue; + } + + $uses[$use->getShortName()] = $use; + } + + return [$namespaceAnalysis, $uses]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzer.php new file mode 100644 index 0000000..3f0738c --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class PhpUnitTestCaseAnalyzer +{ + /** + * Returns an indices of PHPUnit classes in reverse appearance order. + * Order is important - it's reverted, so if we inject tokens into collection, + * we do it for bottom of file first, and then to the top of the file, so we + * mitigate risk of not visiting whole collections (final indices). + * + * @return iterable array of [int start, int end] indices from later to earlier classes + */ + public function findPhpUnitClasses(Tokens $tokens): iterable + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$this->isPhpUnitClass($tokens, $index)) { + continue; + } + + $startIndex = $tokens->getNextTokenOfKind($index, ['{']); + \assert(\is_int($startIndex)); + + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $startIndex); + + yield [$startIndex, $endIndex]; + } + } + + private function isPhpUnitClass(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->isGivenKind(\T_CLASS)) { + return false; + } + + $extendsIndex = $tokens->getNextTokenOfKind($index, ['{', [\T_EXTENDS]]); + + if (!$tokens[$extendsIndex]->isGivenKind(\T_EXTENDS)) { + return false; + } + + if (Preg::match('/(?:Test|TestCase)$/', $tokens[$index]->getContent())) { + return true; + } + + while (null !== $index = $tokens->getNextMeaningfulToken($index)) { + if ($tokens[$index]->equals('{')) { + break; // end of class signature + } + + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; // not part of extends nor part of implements; so continue + } + + if (Preg::match('/(?:Test|TestCase)(?:Interface)?$/', $tokens[$index]->getContent())) { + return true; + } + } + + return false; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php new file mode 100644 index 0000000..e7642c3 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class RangeAnalyzer +{ + private function __construct() + { + // cannot create instance of util. class + } + + /** + * Meaningful compare of tokens within ranges. + * + * @param array{start: int, end: int} $range1 + * @param array{start: int, end: int} $range2 + */ + public static function rangeEqualsRange(Tokens $tokens, array $range1, array $range2): bool + { + $leftStart = $range1['start']; + $leftEnd = $range1['end']; + + if ($tokens[$leftStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + } + + while ($tokens[$leftStart]->equals('(') && $tokens[$leftEnd]->equals(')')) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $leftEnd = $tokens->getPrevMeaningfulToken($leftEnd); + } + + $rightStart = $range2['start']; + $rightEnd = $range2['end']; + + if ($tokens[$rightStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + } + + while ($tokens[$rightStart]->equals('(') && $tokens[$rightEnd]->equals(')')) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + $rightEnd = $tokens->getPrevMeaningfulToken($rightEnd); + } + + $arrayOpenTypes = ['[', [CT::T_ARRAY_INDEX_BRACE_OPEN]]; + $arrayCloseTypes = [']', [CT::T_ARRAY_INDEX_BRACE_CLOSE]]; + + while (true) { + $leftToken = $tokens[$leftStart]; + $rightToken = $tokens[$rightStart]; + + if ( + !$leftToken->equals($rightToken) + && !($leftToken->equalsAny($arrayOpenTypes) && $rightToken->equalsAny($arrayOpenTypes)) + && !($leftToken->equalsAny($arrayCloseTypes) && $rightToken->equalsAny($arrayCloseTypes)) + ) { + return false; + } + + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + + $reachedLeftEnd = null === $leftStart || $leftStart > $leftEnd; // reached end left or moved over + $reachedRightEnd = null === $rightStart || $rightStart > $rightEnd; // reached end right or moved over + + if (!$reachedLeftEnd && !$reachedRightEnd) { + continue; + } + + return $reachedLeftEnd && $reachedRightEnd; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php new file mode 100644 index 0000000..7404bfd --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @author Kuba Werłos + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReferenceAnalyzer +{ + public function isReference(Tokens $tokens, int $index): bool + { + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + return true; + } + + if (!$tokens[$index]->equals('&')) { + return false; + } + + /** @var int $index */ + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->equalsAny(['=', [\T_AS], [\T_CALLABLE], [\T_DOUBLE_ARROW], [CT::T_ARRAY_TYPEHINT]])) { + return true; + } + + if ($tokens[$index]->isGivenKind(\T_STRING)) { + $index = $tokens->getPrevMeaningfulToken($index); + } + + return $tokens[$index]->equalsAny(['(', ',', [\T_NS_SEPARATOR], [CT::T_NULLABLE_TYPE]]); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php new file mode 100644 index 0000000..afa6df6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/SwitchAnalyzer.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SwitchAnalyzer +{ + /** @var array> */ + private static array $cache = []; + + public static function belongsToSwitch(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals(':')) { + return false; + } + + $collectionHash = $tokens->getCollectionHash(); + + if (!\array_key_exists($collectionHash, self::$cache)) { + self::$cache[$collectionHash] = self::getColonIndicesForSwitch(clone $tokens); + } + + $arr = self::$cache[$collectionHash]; + + return \in_array($index, $arr, true); + } + + /** + * @return list + */ + private static function getColonIndicesForSwitch(Tokens $tokens): array + { + $colonIndices = []; + + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + if ($tokens[$analysis->getOpenIndex()]->equals(':')) { + $colonIndices[] = $analysis->getOpenIndex(); + } + + foreach ($analysis->getCases() as $case) { + $colonIndices[] = $case->getColonIndex(); + } + + $defaultAnalysis = $analysis->getDefaultAnalysis(); + + if (null !== $defaultAnalysis) { + $colonIndices[] = $defaultAnalysis->getColonIndex(); + } + } + + return $colonIndices; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php new file mode 100644 index 0000000..55098a4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WhitespacesAnalyzer +{ + public static function detectIndent(Tokens $tokens, int $index): string + { + while (true) { + $whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[\T_WHITESPACE]]); + + if (null === $whitespaceIndex) { + return ''; + } + + $whitespaceToken = $tokens[$whitespaceIndex]; + + if (str_contains($whitespaceToken->getContent(), "\n")) { + break; + } + + $prevToken = $tokens[$whitespaceIndex - 1]; + + if ($prevToken->isGivenKind([\T_OPEN_TAG, \T_COMMENT]) && "\n" === substr($prevToken->getContent(), -1)) { + break; + } + + $index = $whitespaceIndex; + } + + $explodedContent = explode("\n", $whitespaceToken->getContent()); + + return end($explodedContent); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php new file mode 100644 index 0000000..593e6b8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php @@ -0,0 +1,173 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class CT +{ + /** @deprecated use T_ARRAY_INDEX_BRACE_CLOSE instead */ + public const T_ARRAY_INDEX_CURLY_BRACE_CLOSE = self::T_ARRAY_INDEX_BRACE_CLOSE; + public const T_ARRAY_INDEX_BRACE_CLOSE = 10_001; + + /** @deprecated use T_ARRAY_INDEX_BRACE_OPEN instead */ + public const T_ARRAY_INDEX_CURLY_BRACE_OPEN = self::T_ARRAY_INDEX_BRACE_OPEN; + public const T_ARRAY_INDEX_BRACE_OPEN = 10_002; + + /** @deprecated use T_ARRAY_BRACKET_CLOSE instead */ + public const T_ARRAY_SQUARE_BRACE_CLOSE = self::T_ARRAY_BRACKET_CLOSE; + public const T_ARRAY_BRACKET_CLOSE = 10_003; + + /** @deprecated use T_ARRAY_BRACKET_OPEN instead */ + public const T_ARRAY_SQUARE_BRACE_OPEN = self::T_ARRAY_BRACKET_OPEN; + public const T_ARRAY_BRACKET_OPEN = 10_004; + + public const T_ARRAY_TYPEHINT = 10_005; + + /** @deprecated use T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE instead */ + public const T_BRACE_CLASS_INSTANTIATION_CLOSE = self::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE; + public const T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE = 10_006; + + /** @deprecated use T_CLASS_INSTANTIATION_PARENTHESIS_OPEN instead */ + public const T_BRACE_CLASS_INSTANTIATION_OPEN = self::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN; + public const T_CLASS_INSTANTIATION_PARENTHESIS_OPEN = 10_007; + + public const T_CLASS_CONSTANT = 10_008; + + public const T_CONST_IMPORT = 10_009; + + public const T_CURLY_CLOSE = 10_010; // We explicitly use CURLY part in name to mimic built-in \T_CURLY_OPEN + + /** @deprecated use T_DESTRUCTURING_BRACKET_CLOSE instead */ + public const T_DESTRUCTURING_SQUARE_BRACE_CLOSE = self::T_DESTRUCTURING_BRACKET_CLOSE; + public const T_DESTRUCTURING_BRACKET_CLOSE = 10_011; + + /** @deprecated use T_DESTRUCTURING_BRACKET_OPEN instead */ + public const T_DESTRUCTURING_SQUARE_BRACE_OPEN = self::T_DESTRUCTURING_BRACKET_OPEN; + public const T_DESTRUCTURING_BRACKET_OPEN = 10_012; + + public const T_DOLLAR_CLOSE_CURLY_BRACES = 10_013; // We explicitly use CURLY part in name to mimic built-in \T_DOLLAR_OPEN_CURLY_BRACES + + public const T_DYNAMIC_PROP_BRACE_CLOSE = 10_014; + + public const T_DYNAMIC_PROP_BRACE_OPEN = 10_015; + + public const T_DYNAMIC_VAR_BRACE_CLOSE = 10_016; + + public const T_DYNAMIC_VAR_BRACE_OPEN = 10_017; + + public const T_FUNCTION_IMPORT = 10_018; + + public const T_GROUP_IMPORT_BRACE_CLOSE = 10_019; + + public const T_GROUP_IMPORT_BRACE_OPEN = 10_020; + + public const T_NAMESPACE_OPERATOR = 10_021; + + public const T_NULLABLE_TYPE = 10_022; + + public const T_RETURN_REF = 10_023; + + public const T_TYPE_ALTERNATION = 10_024; + + public const T_TYPE_COLON = 10_025; + + public const T_USE_LAMBDA = 10_026; + + public const T_USE_TRAIT = 10_027; + + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC = 10_028; + + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED = 10_029; + + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE = 10_030; + + public const T_ATTRIBUTE_CLOSE = 10_031; // We explicitly skip BRACKET part in name to mimic built-in \T_ATTRIBUTE + + public const T_NAMED_ARGUMENT_NAME = 10_032; + + public const T_NAMED_ARGUMENT_COLON = 10_033; + + public const T_FIRST_CLASS_CALLABLE = 10_034; + + public const T_TYPE_INTERSECTION = 10_035; + + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN = 10_036; + + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE = 10_037; + + /** @deprecated use T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN instead */ + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN = self::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN = 10_038; + + /** @deprecated use T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE instead */ + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE = self::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE = 10_039; + + public const T_PROPERTY_HOOK_BRACE_OPEN = 10_040; + public const T_PROPERTY_HOOK_BRACE_CLOSE = 10_041; + + private function __construct() {} + + /** + * Get name for custom token. + * + * @param int $value custom token value + * + * @return non-empty-string + */ + public static function getName(int $value): string + { + if (!self::has($value)) { + throw new \InvalidArgumentException(\sprintf('No custom token was found for "%s".', $value)); + } + + $tokens = self::getMapById(); + + \assert(isset($tokens[$value])); + + return 'CT::'.$tokens[$value]; + } + + /** + * Check if given custom token exists. + * + * @param int $value custom token value + */ + public static function has(int $value): bool + { + $tokens = self::getMapById(); + + return isset($tokens[$value]); + } + + /** + * @return array + */ + private static function getMapById(): array + { + static $constants; + + if (null === $constants) { + $reflection = new \ReflectionClass(self::class); + $constants = array_flip($reflection->getConstants()); + } + + return $constants; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/FCT.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/FCT.php new file mode 100644 index 0000000..b6f7cd8 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/FCT.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * Forward Compatibility Tokens. + * + * Class containing tokens that are not present in the lowest supported PHP version, + * so the code can always use the class constant, instead of checking if the constant is defined + * + * @TODO PHP 8.0+, when mentioned PHP version is required, remove the related consts + * @TODO PHP 8.1+, when mentioned PHP version is required, remove the related consts + * @TODO PHP 8.4+, when mentioned PHP version is required, remove the related consts + * @TODO PHP 8.5+, when mentioned PHP version is required, remove the related consts + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FCT +{ + // PHP 8.0+ + public const T_ATTRIBUTE = \PHP_VERSION_ID >= 8_00_00 ? \T_ATTRIBUTE : -801; + public const T_MATCH = \PHP_VERSION_ID >= 8_00_00 ? \T_MATCH : -802; + public const T_NULLSAFE_OBJECT_OPERATOR = \PHP_VERSION_ID >= 8_00_00 ? \T_NULLSAFE_OBJECT_OPERATOR : -803; + public const T_NAME_FULLY_QUALIFIED = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_FULLY_QUALIFIED : -804; + public const T_NAME_QUALIFIED = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_QUALIFIED : -805; + public const T_NAME_RELATIVE = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_RELATIVE : -806; + + // PHP 8.1+ + public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = \PHP_VERSION_ID >= 8_01_00 ? \T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG : -811; + public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = \PHP_VERSION_ID >= 8_01_00 ? \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG : -812; + public const T_ENUM = \PHP_VERSION_ID >= 8_01_00 ? \T_ENUM : -813; + public const T_READONLY = \PHP_VERSION_ID >= 8_01_00 ? \T_READONLY : -814; + + // PHP 8.4+ + public const T_PRIVATE_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PRIVATE_SET : -841; + public const T_PROTECTED_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PROTECTED_SET : -842; + public const T_PUBLIC_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PUBLIC_SET : -843; + public const T_PROPERTY_C = \PHP_VERSION_ID >= 8_04_00 ? \T_PROPERTY_C : -844; + + // PHP 8.5+ + public const T_PIPE = \PHP_VERSION_ID >= 8_05_00 ? \T_PIPE : -851; + public const T_VOID_CAST = \PHP_VERSION_ID >= 8_05_00 ? \T_VOID_CAST : -852; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Processor/ImportProcessor.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Processor/ImportProcessor.php new file mode 100644 index 0000000..6fa28f4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Processor/ImportProcessor.php @@ -0,0 +1,111 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Processor; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\WhitespacesFixerConfig; + +/** + * @author Greg Korba + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ImportProcessor +{ + private WhitespacesFixerConfig $whitespacesConfig; + + public function __construct(WhitespacesFixerConfig $whitespacesConfig) + { + $this->whitespacesConfig = $whitespacesConfig; + } + + /** + * @param array{ + * const?: array, + * class?: array, + * function?: array + * } $imports + */ + public function insertImports(Tokens $tokens, array $imports, int $atIndex): void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + + $prevIndex = $tokens->getPrevMeaningfulToken($atIndex); + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_OPEN_TAG_WITH_ECHO)) { + $tokens->insertAt($prevIndex, Tokens::fromCode("")); + $atIndex = $prevIndex + 1; + } + + if (!$tokens[$atIndex]->isWhitespace() || !str_contains($tokens[$atIndex]->getContent(), "\n")) { + $tokens->insertAt($atIndex, new Token([\T_WHITESPACE, $lineEnding])); + } + + foreach ($imports as $type => $typeImports) { + sort($typeImports); + + $items = []; + + foreach ($typeImports as $name) { + $items = array_merge($items, [ + new Token([\T_WHITESPACE, $lineEnding]), + new Token([\T_USE, 'use']), + new Token([\T_WHITESPACE, ' ']), + ]); + + if ('const' === $type) { + $items[] = new Token([CT::T_CONST_IMPORT, 'const']); + $items[] = new Token([\T_WHITESPACE, ' ']); + } elseif ('function' === $type) { + $items[] = new Token([CT::T_FUNCTION_IMPORT, 'function']); + $items[] = new Token([\T_WHITESPACE, ' ']); + } + + $items = array_merge($items, self::tokenizeName($name)); + $items[] = new Token(';'); + } + + $tokens->insertAt($atIndex, $items); + } + } + + /** + * @param non-empty-string $name + * + * @return list + */ + public static function tokenizeName(string $name): array + { + $parts = explode('\\', $name); + $newTokens = []; + + if ('' === $parts[0]) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + array_shift($parts); + } + + foreach ($parts as $part) { + $newTokens[] = new Token([\T_STRING, $part]); + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + + array_pop($newTokens); + + return $newTokens; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php new file mode 100644 index 0000000..ebfba79 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php @@ -0,0 +1,528 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Future; + +/** + * Representation of single token. + * As a token prototype you should understand a single element generated by token_get_all. + * Also, this class exposes PHPStan types. (hint: string in those types shall ideally not be empty - yet we are not there yet). + * + * @phpstan-type _PhpTokenKind int|string + * @phpstan-type _PhpTokenArray array{0: int, 1: string, 2?: int} + * @phpstan-type _PhpTokenArrayPartial array{0: int, 1?: string, 2?: int} + * @phpstan-type _PhpTokenPrototype _PhpTokenArray|string + * @phpstan-type _PhpTokenPrototypePartial _PhpTokenArrayPartial|string + * + * @author Dariusz Rumiński + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Token +{ + /** + * Content of token prototype. + */ + private string $content; + + /** + * ID of token prototype, if available. + */ + private ?int $id; + + /** + * If token prototype is an array. + */ + private bool $isArray; + + /** + * @param _PhpTokenPrototype $token token prototype + */ + public function __construct($token) + { + if (\is_array($token)) { + if (!\is_int($token[0])) { + throw new \InvalidArgumentException(\sprintf( + 'Id must be an int, got "%s".', + get_debug_type($token[0]), + )); + } + + if (!\is_string($token[1])) { + throw new \InvalidArgumentException(\sprintf( + 'Content must be a string, got "%s".', + get_debug_type($token[1]), + )); + } + + \assert(!isset($token[2]) || \is_int($token[2])); // only assertion as we do not use the value anywhere + + if ('' === $token[1]) { + throw new \InvalidArgumentException('Cannot set empty content for id-based Token.'); + } + + $this->isArray = true; + $this->id = $token[0]; + $this->content = $token[1]; + } elseif (\is_string($token)) { + $this->isArray = false; + $this->id = null; + $this->content = $token; + } else { + throw new \InvalidArgumentException(\sprintf('Cannot recognize input value as valid Token prototype, got "%s".', get_debug_type($token))); + } + } + + /** + * @return non-empty-list + */ + public static function getCastTokenKinds(): array + { + return [\T_ARRAY_CAST, \T_BOOL_CAST, \T_DOUBLE_CAST, \T_INT_CAST, \T_OBJECT_CAST, \T_STRING_CAST, \T_UNSET_CAST, FCT::T_VOID_CAST]; + } + + /** + * Get classy tokens kinds: T_ENUM, T_CLASS, T_INTERFACE and T_TRAIT. + * + * @return non-empty-list + */ + public static function getClassyTokenKinds(): array + { + return [\T_CLASS, \T_TRAIT, \T_INTERFACE, FCT::T_ENUM]; + } + + /** + * Get object operator tokens kinds: T_OBJECT_OPERATOR and (if available) T_NULLSAFE_OBJECT_OPERATOR. + * + * @return non-empty-list + */ + public static function getObjectOperatorKinds(): array + { + return [\T_OBJECT_OPERATOR, FCT::T_NULLSAFE_OBJECT_OPERATOR]; + } + + /** + * Check if token is equals to given one. + * + * If tokens are arrays, then only keys defined in parameter token are checked. + * + * @param _PhpTokenPrototypePartial|Token $other token or it's prototype + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equals($other, bool $caseSensitive = true): bool + { + if ('&' === $other) { + return '&' === $this->content && (null === $this->id || $this->isGivenKind([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + if (null === $this->id && '&' === $this->content) { + return $other instanceof self && '&' === $other->content && (null === $other->id || $other->isGivenKind([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + + if ($other instanceof self) { + // Inlined getPrototype() on this very hot path. + // We access the private properties of $other directly to save function call overhead. + // This is only possible because $other is of the same class as `self`. + if (!$other->isArray) { + $otherPrototype = $other->content; + } else { + $otherPrototype = [ + $other->id, + $other->content, + ]; + } + } else { + $otherPrototype = $other; + } + + if ($this->isArray !== \is_array($otherPrototype)) { + return false; + } + + if (!$this->isArray) { + return $this->content === $otherPrototype; + } + + if ($this->id !== $otherPrototype[0]) { + return false; + } + + if (isset($otherPrototype[1])) { + if ($caseSensitive) { + if ($this->content !== $otherPrototype[1]) { + return false; + } + } elseif (0 !== strcasecmp($this->content, $otherPrototype[1])) { + return false; + } + } + + \assert(!isset($otherPrototype[2]) || \is_int($otherPrototype[2])); // only assertion as we do not use the value anywhere + + // detect unknown keys + unset($otherPrototype[0], $otherPrototype[1]); + + return [] === $otherPrototype; + } + + /** + * Check if token is equals to one of given. + * + * @param list<_PhpTokenPrototypePartial|Token> $others array of tokens or token prototypes + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equalsAny(array $others, bool $caseSensitive = true): bool + { + foreach ($others as $other) { + if ($this->equals($other, $caseSensitive)) { + return true; + } + } + + return false; + } + + /** + * A helper method used to find out whether a certain input token has to be case-sensitively matched. + * + * @param array|bool $caseSensitive global case sensitiveness or an array of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * @param int $key the key of the token that has to be looked up + * + * @deprecated + */ + public static function isKeyCaseSensitive($caseSensitive, int $key): bool + { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Method "%s" is deprecated and will be removed in the next major version.', + __METHOD__, + ))); + + if (\is_array($caseSensitive)) { + return $caseSensitive[$key] ?? true; + } + + return $caseSensitive; + } + + /** + * @return array{int, non-empty-string}|string + */ + public function getPrototype() + { + if (!$this->isArray) { + return $this->content; + } + + \assert('' !== $this->content); + + return [ + $this->id, + $this->content, + ]; + } + + /** + * Get token's content. + * + * It shall be used only for getting the content of token, not for checking it against excepted value. + */ + public function getContent(): string + { + return $this->content; + } + + /** + * Get token's id. + * + * It shall be used only for getting the internal id of token, not for checking it against excepted value. + */ + public function getId(): ?int + { + return $this->id; + } + + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|non-empty-string token name + */ + public function getName(): ?string + { + if (null === $this->id) { + return null; + } + + return self::getNameForId($this->id); + } + + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|non-empty-string token name + */ + public static function getNameForId(int $id): ?string + { + if (CT::has($id)) { + return CT::getName($id); + } + + $name = token_name($id); + + return 'UNKNOWN' === $name ? null : $name; + } + + /** + * Generate array containing all keywords that exists in PHP version in use. + * + * @return non-empty-list + */ + public static function getKeywords(): array + { + static $keywords = null; + + if (null === $keywords) { + $keywords = self::getTokenKindsForNames(['T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE', + 'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO', + 'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH', + 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL', + 'T_FINALLY', 'T_FN', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER', + 'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF', + 'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR', + 'T_NAMESPACE', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE', + 'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY', + 'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'T_YIELD_FROM', + ]) + [ + CT::T_ARRAY_TYPEHINT => CT::T_ARRAY_TYPEHINT, + CT::T_CLASS_CONSTANT => CT::T_CLASS_CONSTANT, + CT::T_CONST_IMPORT => CT::T_CONST_IMPORT, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_FUNCTION_IMPORT => CT::T_FUNCTION_IMPORT, + CT::T_NAMESPACE_OPERATOR => CT::T_NAMESPACE_OPERATOR, + CT::T_USE_LAMBDA => CT::T_USE_LAMBDA, + CT::T_USE_TRAIT => CT::T_USE_TRAIT, + FCT::T_ENUM => FCT::T_ENUM, + FCT::T_MATCH => FCT::T_MATCH, + FCT::T_PRIVATE_SET => FCT::T_PRIVATE_SET, + FCT::T_PROTECTED_SET => FCT::T_PROTECTED_SET, + FCT::T_PUBLIC_SET => FCT::T_PUBLIC_SET, + FCT::T_READONLY => FCT::T_READONLY, + ]; + } + + return $keywords; + } + + /** + * Generate array containing all predefined constants that exists in PHP version in use. + * + * @return non-empty-array + * + * @see https://php.net/manual/en/language.constants.predefined.php + */ + public static function getMagicConstants(): array + { + static $magicConstants = null; + + if (null === $magicConstants) { + $magicConstants = self::getTokenKindsForNames(['T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C']); + } + + return $magicConstants; + } + + /** + * Check if token prototype is an array. + * + * @return bool is array + * + * @phpstan-assert-if-true !=null $this->getId() + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isArray(): bool + { + return $this->isArray; + } + + /** + * Check if token is one of type cast tokens. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isCast(): bool + { + return $this->isGivenKind(self::getCastTokenKinds()); + } + + /** + * Check if token is one of classy tokens: T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isClassy(): bool + { + return $this->isGivenKind(self::getClassyTokenKinds()); + } + + /** + * Check if token is one of comment tokens: T_COMMENT or T_DOC_COMMENT. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isComment(): bool + { + return $this->isGivenKind([\T_COMMENT, \T_DOC_COMMENT]); + } + + /** + * Check if token is one of object operator tokens: T_OBJECT_OPERATOR or T_NULLSAFE_OBJECT_OPERATOR. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isObjectOperator(): bool + { + return $this->isGivenKind(self::getObjectOperatorKinds()); + } + + /** + * Check if token is one of given kind. + * + * @param int|list $possibleKind kind or array of kinds + * + * @phpstan-assert-if-true !=null $this->getId() + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isGivenKind($possibleKind): bool + { + return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, true) : $this->id === $possibleKind); + } + + /** + * Check if token is a keyword. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isKeyword(): bool + { + $keywords = self::getKeywords(); + + return $this->isArray && isset($keywords[$this->id]); + } + + /** + * Check if token is a native PHP constant: true, false or null. + * + * @phpstan-assert-if-true !='' $this->getContent() + */ + public function isNativeConstant(): bool + { + return $this->isArray && \in_array(strtolower($this->content), ['true', 'false', 'null'], true); + } + + /** + * Returns if the token is of a Magic constants type. + * + * @phpstan-assert-if-true !='' $this->getContent() + * + * @see https://php.net/manual/en/language.constants.predefined.php + */ + public function isMagicConstant(): bool + { + $magicConstants = self::getMagicConstants(); + + return $this->isArray && isset($magicConstants[$this->id]); + } + + /** + * Check if token is whitespace. + * + * @param null|string $whitespaces whitespace characters, default is " \t\n\r\0\x0B" + */ + public function isWhitespace(?string $whitespaces = " \t\n\r\0\x0B"): bool + { + if (null === $whitespaces) { + $whitespaces = " \t\n\r\0\x0B"; + } + + if ($this->isArray && !$this->isGivenKind(\T_WHITESPACE)) { + return false; + } + + return '' === trim($this->content, $whitespaces); + } + + /** + * @return array{ + * id: null|int, + * name: null|non-empty-string, + * content: string, + * isArray: bool, + * changed: bool, + * } + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'name' => $this->getName(), + 'content' => $this->content, + 'isArray' => $this->isArray, + 'changed' => false, // @TODO v4: remove index + ]; + } + + /** + * @return non-empty-string + */ + public function toJson(): string + { + try { + return json_encode($this->toArray(), \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); + } catch (\JsonException $e) { + return json_encode( + [ + 'errorDescription' => 'Cannot encode Tokens to JSON.', + 'rawErrorMessage' => $e->getMessage(), + ], + \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK, + ); + } + } + + /** + * @param non-empty-list $tokenNames + * + * @return non-empty-array + */ + private static function getTokenKindsForNames(array $tokenNames): array + { + $keywords = []; + foreach ($tokenNames as $keywordName) { + $keyword = \constant($keywordName); + $keywords[$keyword] = $keyword; + } + + return $keywords; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php new file mode 100644 index 0000000..0d18a41 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php @@ -0,0 +1,1657 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Console\Application; +use PhpCsFixer\Future; +use PhpCsFixer\Hasher; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; + +/** + * Collection of code tokens. + * + * Its role is to provide the ability to manage collection and navigate through it. + * + * As a token prototype you should understand a single element generated by token_get_all. + * + * @extends \SplFixedArray + * + * `SplFixedArray` uses `T|null` in return types because value can be null if an offset is unset or if the size does not match the number of elements. + * But our class takes care of it and always ensures correct size and indexes, so that these methods never return `null` instead of `Token`. + * + * @method Token offsetGet($offset) + * @method \Iterator getIterator() + * @method array toArray() + * + * @phpstan-import-type _PhpTokenKind from Token + * @phpstan-import-type _PhpTokenArray from Token + * @phpstan-import-type _PhpTokenArrayPartial from Token + * @phpstan-import-type _PhpTokenPrototype from Token + * @phpstan-import-type _PhpTokenPrototypePartial from Token + * + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0: mark as final + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +class Tokens extends \SplFixedArray +{ + /** @deprecated use BLOCK_TYPE_PARENTHESIS instead */ + public const BLOCK_TYPE_PARENTHESIS_BRACE = self::BLOCK_TYPE_PARENTHESIS; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_PARENTHESIS = 1; + + /** @deprecated use BLOCK_TYPE_BRACE instead */ + public const BLOCK_TYPE_CURLY_BRACE = self::BLOCK_TYPE_BRACE; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_BRACE = 2; + + /** @deprecated use BLOCK_TYPE_INDEX_BRACKET instead */ + public const BLOCK_TYPE_INDEX_SQUARE_BRACE = self::BLOCK_TYPE_INDEX_BRACKET; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_INDEX_BRACKET = 3; + + /** @deprecated use BLOCK_TYPE_ARRAY_BRACKET instead */ + public const BLOCK_TYPE_ARRAY_SQUARE_BRACE = self::BLOCK_TYPE_ARRAY_BRACKET; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_ARRAY_BRACKET = 4; + + public const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5; + + public const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6; + + /** @deprecated use BLOCK_TYPE_INDEX_BRACE instead */ + public const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = self::BLOCK_TYPE_INDEX_BRACE; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_INDEX_BRACE = 7; + + public const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8; + + /** @deprecated use BLOCK_TYPE_DESTRUCTURING_BRACKET instead */ + public const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = self::BLOCK_TYPE_DESTRUCTURING_BRACKET; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_DESTRUCTURING_BRACKET = 9; + + /** @deprecated use BLOCK_TYPE_CLASS_INSTANTIATION_PARENTHESIS instead */ + public const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = self::BLOCK_TYPE_CLASS_INSTANTIATION_PARENTHESIS; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_CLASS_INSTANTIATION_PARENTHESIS = 10; + + public const BLOCK_TYPE_ATTRIBUTE = 11; + + public const BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS = 12; + + /** @deprecated use BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE instead */ + public const BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE = self::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE; // @phpstan-ignore shipmonk.deadConstant + public const BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE = 13; + + public const BLOCK_TYPE_COMPLEX_STRING_VARIABLE = 14; + + public const BLOCK_TYPE_PROPERTY_HOOK = 15; + + /** + * Static class cache. + * + * @var array + */ + private static array $cache = []; + + /** + * Cache of block starts. Any change in collection will invalidate it. + * + * @var array + */ + private array $blockStartCache = []; + + /** + * Cache of block ends. Any change in collection will invalidate it. + * + * @var array + */ + private array $blockEndCache = []; + + /** + * An hash of the code string. + * + * @var ?non-empty-string + */ + private ?string $codeHash = null; + + /** + * An hash of the collection items. + * + * @var ?non-empty-string + */ + private ?string $collectionHash = null; + + /** + * Flag is collection was changed. + * + * It doesn't know about change of collection's items. To check it run `isChanged` method. + */ + private bool $changed = false; + + /** + * Set of found token kinds. + * + * When the token kind is present in this set it means that given token kind + * was ever seen inside the collection (but may not be part of it any longer). + * The key is token kind and the value is the number of occurrences. + * + * @var array<_PhpTokenKind, int<0, max>> + */ + private array $foundTokenKinds = []; + + /** + * @var null|list + */ + private ?array $namespaceDeclarations = null; + + /** + * Clone tokens collection. + */ + public function __clone() + { + foreach ($this as $key => $val) { + $this[$key] = clone $val; + } + } + + /** + * Clear cache - one position or all of them. + * + * @param null|non-empty-string $key position to clear, when null clear all + */ + public static function clearCache(?string $key = null): void + { + if (null === $key) { + self::$cache = []; + + return; + } + + unset(self::$cache[$key]); + } + + /** + * Detect type of block. + * + * @return null|array{type: self::BLOCK_TYPE_*, isStart: bool} + */ + public static function detectBlockType(Token $token): ?array + { + static $blockEdgeKinds = null; + + if (null === $blockEdgeKinds) { + $blockEdgeKinds = []; + foreach (self::getBlockEdgeDefinitions() as $type => $definition) { + $blockEdgeKinds[ + \is_string($definition['start']) ? $definition['start'] : $definition['start'][0] + ] = ['type' => $type, 'isStart' => true]; + $blockEdgeKinds[ + \is_string($definition['end']) ? $definition['end'] : $definition['end'][0] + ] = ['type' => $type, 'isStart' => false]; + } + } + + // inlined extractTokenKind() call on the hot path + $tokenKind = $token->isArray() ? $token->getId() : $token->getContent(); + + return $blockEdgeKinds[$tokenKind] ?? null; + } + + /** + * Create token collection from array. + * + * @param array $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null): self + { + $tokens = new self(\count($array)); + + if (false !== $saveIndices && !array_is_list($array)) { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Parameter "array" should be a list. This will be enforced in version %d.0.', + Application::getMajorVersion() + 1, + ))); + + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + + $tokens->clearChanged(); + $tokens->generateCode(); // ensure code hash is calculated, so it's registered in cache + + return $tokens; + } + + /** + * Create token collection directly from code. + * + * @param string $code PHP code + */ + public static function fromCode(string $code): self + { + $codeHash = self::calculateHash($code); + + if (self::hasCache($codeHash)) { + $tokens = self::getCache($codeHash); + + if ($codeHash === $tokens->codeHash) { + $tokens->clearEmptyTokens(); + $tokens->clearChanged(); + + return $tokens; + } + } + + $tokens = new self(); + $tokens->setCode($code); + $tokens->clearChanged(); + + return $tokens; + } + + /** + * @return array + */ + public static function getBlockEdgeDefinitions(): array + { + // @FRS TODO sprawdzic spojnosc na koniec + return [ + self::BLOCK_TYPE_BRACE => [ + 'start' => '{', + 'end' => '}', + ], + self::BLOCK_TYPE_PARENTHESIS => [ + 'start' => '(', + 'end' => ')', + ], + self::BLOCK_TYPE_INDEX_BRACKET => [ + 'start' => '[', + 'end' => ']', + ], + self::BLOCK_TYPE_ARRAY_BRACKET => [ + 'start' => [CT::T_ARRAY_BRACKET_OPEN, '['], + 'end' => [CT::T_ARRAY_BRACKET_CLOSE, ']'], + ], + self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => [ + 'start' => [CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => [ + 'start' => [CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_INDEX_BRACE => [ + 'start' => [CT::T_ARRAY_INDEX_BRACE_OPEN, '{'], + 'end' => [CT::T_ARRAY_INDEX_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_GROUP_IMPORT_BRACE => [ + 'start' => [CT::T_GROUP_IMPORT_BRACE_OPEN, '{'], + 'end' => [CT::T_GROUP_IMPORT_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_DESTRUCTURING_BRACKET => [ + 'start' => [CT::T_DESTRUCTURING_BRACKET_OPEN, '['], + 'end' => [CT::T_DESTRUCTURING_BRACKET_CLOSE, ']'], + ], + self::BLOCK_TYPE_CLASS_INSTANTIATION_PARENTHESIS => [ + 'start' => [CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN, '('], + 'end' => [CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE, ')'], + ], + self::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS => [ + 'start' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('], + 'end' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'], + ], + self::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE => [ + 'start' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN, '{'], + 'end' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_COMPLEX_STRING_VARIABLE => [ + 'start' => [\T_DOLLAR_OPEN_CURLY_BRACES, '${'], + 'end' => [CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}'], + ], + self::BLOCK_TYPE_PROPERTY_HOOK => [ + 'start' => [CT::T_PROPERTY_HOOK_BRACE_OPEN, '{'], + 'end' => [CT::T_PROPERTY_HOOK_BRACE_CLOSE, '}'], + ], + self::BLOCK_TYPE_ATTRIBUTE => [ + 'start' => [FCT::T_ATTRIBUTE, '#['], + 'end' => [CT::T_ATTRIBUTE_CLOSE, ']'], + ], + ]; + } + + /** + * Set new size of collection. + * + * @param int $size + */ + #[\ReturnTypeWillChange] + public function setSize($size): bool + { + throw new \RuntimeException('Changing tokens collection size explicitly is not allowed.'); + } + + /** + * Unset collection item. + * + * @param int $index + */ + public function offsetUnset($index): void + { + if (\count($this) - 1 !== $index) { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Tokens should be a list - only the last index can be unset. This will be enforced in version %d.0.', + Application::getMajorVersion() + 1, + ))); + } + + if (isset($this[$index])) { + if (isset($this->blockStartCache[$index])) { + unset($this->blockEndCache[$this->blockStartCache[$index]], $this->blockStartCache[$index]); + } + if (isset($this->blockEndCache[$index])) { + unset($this->blockStartCache[$this->blockEndCache[$index]], $this->blockEndCache[$index]); + } + + $this->unregisterFoundToken($this[$index]); + + $this->changed = true; + $this->collectionHash = null; + self::clearCache($this->codeHash); + $this->codeHash = null; + $this->namespaceDeclarations = null; + } + + parent::offsetUnset($index); + } + + /** + * Set collection item. + * + * Warning! `$newval` must not be typehinted to be compatible with `ArrayAccess::offsetSet` method. + * + * @param int $index + * @param Token $newval + */ + public function offsetSet($index, $newval): void + { + if (0 > $index || \count($this) <= $index) { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Tokens should be a list - index must be within the existing range. This will be enforced in version %d.0.', + Application::getMajorVersion() + 1, + ))); + } + + if (!$newval instanceof Token) { + Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( + 'Tokens should be a list of Token instances - newval must be a Token. This will be enforced in version %d.0.', + Application::getMajorVersion() + 1, + ))); + } + + if (isset($this[$index])) { + if (isset($this->blockStartCache[$index])) { + unset($this->blockEndCache[$this->blockStartCache[$index]], $this->blockStartCache[$index]); + } + if (isset($this->blockEndCache[$index])) { + unset($this->blockStartCache[$this->blockEndCache[$index]], $this->blockEndCache[$index]); + } + } + + if (!isset($this[$index]) || !$this[$index]->equals($newval)) { + if (isset($this[$index])) { + $this->unregisterFoundToken($this[$index]); + } + + $this->changed = true; + $this->collectionHash = null; + self::clearCache($this->codeHash); + $this->codeHash = null; + $this->namespaceDeclarations = null; + + $this->registerFoundToken($newval); + } + + parent::offsetSet($index, $newval); + } + + /** + * Clear internal flag if collection was changed and flag for all collection's items. + */ + public function clearChanged(): void + { + $this->changed = false; + } + + /** + * Clear empty tokens. + * + * Empty tokens can occur e.g. after calling clear on item of collection. + */ + public function clearEmptyTokens(): void + { + // no empty token found, therefore there is no need to override collection + if (!$this->isTokenKindFound('')) { + return; + } + + $limit = \count($this); + + for ($index = 0; $index < $limit; ++$index) { + if ($this->isEmptyAt($index)) { + break; + } + } + + for ($count = $index; $index < $limit; ++$index) { + if (!$this->isEmptyAt($index)) { + // use directly for speed, skip the register of token kinds found etc. + $buffer = $this[$count]; + parent::offsetSet($count, $this[$index]); + parent::offsetSet($index, $buffer); + + if (isset($this->blockStartCache[$index])) { + $otherEndIndex = $this->blockStartCache[$index]; + unset($this->blockStartCache[$index]); + $this->blockStartCache[$count] = $otherEndIndex; + $this->blockEndCache[$otherEndIndex] = $count; + } + + if (isset($this->blockEndCache[$index])) { + $otherEndIndex = $this->blockEndCache[$index]; + unset($this->blockEndCache[$index]); + $this->blockStartCache[$otherEndIndex] = $count; + $this->blockEndCache[$count] = $otherEndIndex; + } + + ++$count; + } + } + + // we are moving the tokens, we need to clear the index-based Cache + $this->namespaceDeclarations = null; + $this->foundTokenKinds[''] = 0; + + $this->collectionHash = null; + + $this->updateSizeByTrimmingTrailingEmptyTokens(); + } + + /** + * Ensure that on given index is a whitespace with given kind. + * + * If there is a whitespace then it's content will be modified. + * If not - the new Token will be added. + * + * @param int $index index + * @param int $indexOffset index offset for Token insertion + * @param string $whitespace whitespace to set + * + * @return bool if new Token was added + */ + public function ensureWhitespaceAtIndex(int $index, int $indexOffset, string $whitespace): bool + { + $removeLastCommentLine = static function (self $tokens, int $index, int $indexOffset, string $whitespace): string { + $token = $tokens[$index]; + + if (1 === $indexOffset && $token->isGivenKind(\T_OPEN_TAG)) { + if (str_starts_with($whitespace, "\r\n")) { + $tokens[$index] = new Token([\T_OPEN_TAG, rtrim($token->getContent())."\r\n"]); + + return \strlen($whitespace) > 2 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php + ? substr($whitespace, 2) + : ''; + } + + $tokens[$index] = new Token([\T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]); + + return \strlen($whitespace) > 1 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php + ? substr($whitespace, 1) + : ''; + } + + return $whitespace; + }; + + if ($this[$index]->isWhitespace()) { + $whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace); + + if ('' === $whitespace) { + $this->clearAt($index); + } else { + $this[$index] = new Token([\T_WHITESPACE, $whitespace]); + } + + return false; + } + + $whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace); + + if ('' === $whitespace) { + return false; + } + + $this->insertAt( + $index + $indexOffset, + [new Token([\T_WHITESPACE, $whitespace])], + ); + + return true; + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of opening brace + * + * @return int<0, max> index of closing brace + */ + public function findBlockEnd(int $type, int $searchIndex): int + { + return $this->findOppositeBlockEdge($type, $searchIndex, true); + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of closing brace + * + * @return int<0, max> index of opening brace + */ + public function findBlockStart(int $type, int $searchIndex): int + { + return $this->findOppositeBlockEdge($type, $searchIndex, false); + } + + /** + * @param int|non-empty-list $possibleKind kind or array of kinds + * @param int $start optional offset + * @param null|int $end optional limit + * + * @return ($possibleKind is int ? array, Token> : array, Token>>) + */ + public function findGivenKind($possibleKind, int $start = 0, ?int $end = null): array + { + if (null === $end) { + $end = \count($this); + } + + $elements = []; + $possibleKinds = (array) $possibleKind; + + foreach ($possibleKinds as $kind) { + $elements[$kind] = []; + } + + $possibleKinds = array_values(array_filter($possibleKinds, fn ($kind): bool => $this->isTokenKindFound($kind))); + + if (\count($possibleKinds) > 0) { + for ($i = $start; $i < $end; ++$i) { + $token = $this[$i]; + if ($token->isGivenKind($possibleKinds)) { + $elements[$token->getId()][$i] = $token; + } + } + } + + return \is_array($possibleKind) ? $elements : $elements[$possibleKind]; + } + + public function generateCode(): string + { + $code = $this->generatePartialCode(0, \count($this) - 1); + if (null === $this->codeHash) { + $this->changeCodeHash(self::calculateHash($code)); // ensure code hash is calculated, so it's registered in cache + } + + return $code; + } + + /** + * Generate code from tokens between given indices. + * + * @param int $start start index + * @param int $end end index + */ + public function generatePartialCode(int $start, int $end): string + { + $code = ''; + + for ($i = $start; $i <= $end; ++$i) { + $code .= $this[$i]->getContent(); + } + + return $code; + } + + /** + * Get hash of code. + */ + public function getCodeHash(): string + { + if (null === $this->codeHash) { + $code = $this->generatePartialCode(0, \count($this) - 1); + $this->changeCodeHash(self::calculateHash($code)); // ensure code hash is calculated, so it's registered in cache + } + + return $this->codeHash; + } + + /** + * @return non-empty-string + * + * @internal + */ + public function getCollectionHash(): string + { + if (null === $this->collectionHash) { + $this->collectionHash = self::calculateHash( + $this->getCodeHash() + .'#' + .\count($this) + .'#' + .implode( + '', + array_map(static fn (?Token $token): ?int => null !== $token ? $token->getId() : null, $this->toArray()), + ), + ); + } + + return $this->collectionHash; + } + + /** + * Get index for closest next token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNextNonWhitespace(int $index, ?string $whitespaces = null): ?int + { + return $this->getNonWhitespaceSibling($index, 1, $whitespaces); + } + + /** + * Get index for closest next token of given kind. + * + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getNextTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int + { + return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive); + } + + /** + * Get index for closest sibling token which is non whitespace. + * + * @param int $index token index + * @param -1|1 $direction + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNonWhitespaceSibling(int $index, int $direction, ?string $whitespaces = null): ?int + { + while (true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + + if (!$this[$index]->isWhitespace($whitespaces)) { + return $index; + } + } + } + + /** + * Get index for closest previous token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getPrevNonWhitespace(int $index, ?string $whitespaces = null): ?int + { + return $this->getNonWhitespaceSibling($index, -1, $whitespaces); + } + + /** + * Get index for closest previous token of given kind. + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getPrevTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int + { + return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive); + } + + /** + * Get index for closest sibling token of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getTokenOfKindSibling(int $index, int $direction, array $tokens = [], bool $caseSensitive = true): ?int + { + $tokens = array_values( + array_filter( + $tokens, + fn ($token): bool => $this->isTokenKindFound($this->extractTokenKind($token)), + ), + ); + + if (0 === \count($tokens)) { + return null; + } + + while (true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + + if ($this[$index]->equalsAny($tokens, $caseSensitive)) { + return $index; + } + } + } + + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens + */ + public function getTokenNotOfKindSibling(int $index, int $direction, array $tokens = []): ?int + { + return $this->getTokenNotOfKind( + $index, + $direction, + fn (int $a): bool => $this[$a]->equalsAny($tokens), + ); + } + + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $kinds possible tokens kinds + */ + public function getTokenNotOfKindsSibling(int $index, int $direction, array $kinds = []): ?int + { + return $this->getTokenNotOfKind( + $index, + $direction, + fn (int $index): bool => $this[$index]->isGivenKind($kinds), + ); + } + + /** + * Get index for closest sibling token that is not a whitespace, comment or attribute. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getMeaningfulTokenSibling(int $index, int $direction): ?int + { + return $this->getTokenNotOfKindsSibling( + $index, + $direction, + [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT], + ); + } + + /** + * Get index for closest sibling token which is not empty. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getNonEmptySibling(int $index, int $direction): ?int + { + while (true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + + if (!$this->isEmptyAt($index)) { + return $index; + } + } + } + + /** + * Get index for closest next token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getNextMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + + /** + * Get index for closest previous token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getPrevMeaningfulToken(int $index): ?int + { + return $this->getMeaningfulTokenSibling($index, -1); + } + + /** + * Find a sequence of meaningful tokens and returns the array of their locations. + * + * @param non-empty-list<_PhpTokenPrototypePartial|Token> $sequence an array of token (kinds) + * @param int $start start index, defaulting to the start of the file + * @param null|int $end end index, defaulting to the end of the file + * @param array|bool $caseSensitive global case sensitiveness or a list of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * + * @return null|non-empty-array, Token> an array containing the tokens matching the sequence elements, indexed by their position + */ + public function findSequence(array $sequence, int $start = 0, ?int $end = null, $caseSensitive = true): ?array + { + $sequenceCount = \count($sequence); + if (0 === $sequenceCount) { + throw new \InvalidArgumentException('Invalid sequence.'); + } + + // $end defaults to the end of the collection + $end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1); + + if ($start + $sequenceCount - 1 > $end) { + return null; + } + + $nonMeaningFullKind = [\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE]; + + // make sure the sequence content is "meaningful" + foreach ($sequence as $key => $token) { + // if not a Token instance already, we convert it to verify the meaningfulness + if (!$token instanceof Token) { + if (\is_array($token) && !isset($token[1])) { + // fake some content as it is required by the Token constructor, + // although optional for search purposes + $token[1] = 'DUMMY'; + } + + $token = new Token($token); + } + + if ($token->isGivenKind($nonMeaningFullKind)) { + throw new \InvalidArgumentException(\sprintf('Non-meaningful token at position: "%s".', $key)); + } + + if ('' === $token->getContent()) { + throw new \InvalidArgumentException(\sprintf('Non-meaningful (empty) token at position: "%s".', $key)); + } + } + + foreach ($sequence as $token) { + if (!$this->isTokenKindFound($this->extractTokenKind($token))) { + return null; + } + } + + // remove the first token from the sequence, so we can freely iterate through the sequence after a match to + // the first one is found + $firstKey = array_key_first($sequence); + $firstCs = self::isKeyCaseSensitive($caseSensitive, $firstKey); + $firstToken = $sequence[$firstKey]; + unset($sequence[$firstKey]); + + // begin searching for the first token in the sequence (start included) + $index = $start - 1; + while ($index <= $end) { + $index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs); + + // ensure we found a match and didn't get past the end index + if (null === $index || $index > $end) { + return null; + } + + // initialise the result array with the current index + $result = [$index => $this[$index]]; + + // advance cursor to the current position + $currIdx = $index; + + // iterate through the remaining tokens in the sequence + foreach ($sequence as $key => $token) { + $currIdx = $this->getNextMeaningfulToken($currIdx); + + // ensure we didn't go too far + if (null === $currIdx || $currIdx > $end) { + return null; + } + + if (!$this[$currIdx]->equals($token, self::isKeyCaseSensitive($caseSensitive, $key))) { + // not a match, restart the outer loop + continue 2; + } + + // append index to the result array + $result[$currIdx] = $this[$currIdx]; + } + + // do we have a complete match? + // hint: $result is bigger than $sequence since the first token has been removed from the latter + if (\count($sequence) < \count($result)) { + return $result; + } + } + + return null; + } + + /** + * Insert instances of Token inside collection. + * + * @param int $index start inserting index + * @param list|Token|Tokens $items instances of Token to insert + */ + public function insertAt(int $index, $items): void + { + $this->insertSlices([$index => $items]); + } + + /** + * Insert a slices or individual Tokens into multiple places in a single run. + * + * This approach is kind-of an experiment - it's proven to improve performance a lot for big files that needs plenty of new tickets to be inserted, + * like edge case example of 3.7h vs 4s (https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/3996#issuecomment-455617637), + * yet at same time changing a logic of fixers in not-always easy way. + * + * To be discussed: + * - should we always aim to use this method? + * - should we deprecate `insertAt` method ? + * + * The `$slices` parameter is an assoc array, in which: + * - index: starting point for inserting of individual slice, with indices being relatives to original array collection before any Token inserted + * - value under index: a slice of Tokens to be inserted + * + * @internal + * + * @param array|Token|Tokens> $slices + */ + public function insertSlices(array $slices): void + { + $itemsCount = 0; + + foreach ($slices as $slice) { + $itemsCount += \is_array($slice) || $slice instanceof self ? \count($slice) : 1; + } + + if (0 === $itemsCount) { + return; + } + + $this->changed = true; + $this->collectionHash = null; + self::clearCache($this->codeHash); + $this->codeHash = null; + $this->namespaceDeclarations = null; + $this->blockStartCache = []; + $this->blockEndCache = []; + + $oldSize = \count($this); + $this->updateSizeByIncreasingToNewSize($oldSize + $itemsCount); + + krsort($slices); + $farthestSliceIndex = array_key_first($slices); + + // We check only the farthest index, if it's within the size of collection, other indices will be valid too. + if (!\is_int($farthestSliceIndex) || $farthestSliceIndex > $oldSize) { + throw new \OutOfBoundsException(\sprintf('Cannot insert index "%s" outside of collection.', $farthestSliceIndex)); + } + + $previousSliceIndex = $oldSize; + + // since we only move already existing items around, we directly call into SplFixedArray::offset* methods. + // that way we get around additional overhead this class adds with overridden offset* methods. + foreach ($slices as $index => $slice) { + if (!\is_int($index) || $index < 0) { + throw new \OutOfBoundsException(\sprintf('Invalid index "%s".', $index)); + } + + $slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice]; + $sliceCount = \count($slice); + + for ($i = $previousSliceIndex - 1; $i >= $index; --$i) { + parent::offsetSet($i + $itemsCount, $this[$i]); + } + + $previousSliceIndex = $index; + $itemsCount -= $sliceCount; + + foreach ($slice as $indexItem => $item) { + if ('' === $item->getContent()) { + throw new \InvalidArgumentException('Must not add empty token to collection.'); + } + + $this->registerFoundToken($item); + + parent::offsetSet($index + $itemsCount + $indexItem, $item); + } + } + } + + /** + * Check if collection was change: collection itself (like insert new tokens) or any of collection's elements. + */ + public function isChanged(): bool + { + return $this->changed; + } + + public function isEmptyAt(int $index): bool + { + $token = $this[$index]; + + return null === $token->getId() && '' === $token->getContent(); + } + + public function clearAt(int $index): void + { + $this[$index] = new Token(''); + } + + /** + * Override tokens at given range. + * + * @param int $indexStart start overriding index + * @param int $indexEnd end overriding index + * @param array|Tokens $items tokens to insert + */ + public function overrideRange(int $indexStart, int $indexEnd, iterable $items): void + { + $indexToChange = $indexEnd - $indexStart + 1; + $itemsCount = \count($items); + + // If we want to add more items than passed range contains we need to + // add placeholders for overhead items. + if ($itemsCount > $indexToChange) { + $placeholders = []; + + while ($itemsCount > $indexToChange) { + $placeholders[] = new Token('__PLACEHOLDER__'); + ++$indexToChange; + } + + $this->insertAt($indexEnd + 1, $placeholders); + } + + // Override each items. + foreach ($items as $itemIndex => $item) { + $this[$indexStart + $itemIndex] = $item; + } + + // If we want to add fewer tokens than passed range contains then clear + // not needed tokens. + if ($itemsCount < $indexToChange) { + $this->clearRange($indexStart + $itemsCount, $indexEnd); + } + } + + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeLeadingWhitespace(int $index, ?string $whitespaces = null): void + { + $this->removeWhitespaceSafely($index, -1, $whitespaces); + } + + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeTrailingWhitespace(int $index, ?string $whitespaces = null): void + { + $this->removeWhitespaceSafely($index, 1, $whitespaces); + } + + /** + * Set code. Clear all current content and replace it by new Token items generated from code directly. + * + * @param string $code PHP code + */ + public function setCode(string $code): void + { + // No need to work when the code is the same. + // That is how we avoid a lot of work and setting changed flag. + if ($code === $this->generateCode()) { + return; + } + + $this->updateSizeToZero(); // clear memory + + $prevErrorHandler = set_error_handler(static function ($type, $msg, $file, $line, $context = []) use (&$prevErrorHandler) { + // Ignore deprecations triggered by token_get_all for tokenized code. + // It is not the responsibility of PHP CS Fixer to care about deprecations within the code being tokenized. + if (\E_DEPRECATED === $type) { + return true; + } + + return null !== $prevErrorHandler ? $prevErrorHandler($type, $msg, $file, $line, $context) : false; + }); + + try { + $tokens = token_get_all($code, \TOKEN_PARSE); + } finally { + restore_error_handler(); + } + + $this->updateSizeByIncreasingToNewSize(\count($tokens)); // pre-allocate collection size + + foreach ($tokens as $index => $token) { + $this[$index] = new Token($token); + } + + $this->applyTransformers(); + + if (\PHP_VERSION_ID < 8_00_00) { + $this->rewind(); + } + + $this->changed = true; + $this->collectionHash = null; + self::clearCache($this->codeHash); + $this->codeHash = null; + $this->namespaceDeclarations = null; + $this->blockStartCache = []; + $this->blockEndCache = []; + + $this->changeCodeHash(self::calculateHash($code)); // ensure code hash is calculated, so it's registered in cache + } + + public function toJson(): string + { + $output = new \SplFixedArray(\count($this)); + + foreach ($this as $index => $token) { + $output[$index] = $token->toArray(); + } + + if (\PHP_VERSION_ID < 8_00_00) { + $this->rewind(); + } + + return json_encode($output, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); + } + + /** + * Check if all token kinds given as argument are found. + * + * @param list<_PhpTokenKind> $tokenKinds + */ + public function isAllTokenKindsFound(array $tokenKinds): bool + { + foreach ($tokenKinds as $tokenKind) { + if (0 === ($this->foundTokenKinds[$tokenKind] ?? 0)) { + return false; + } + } + + return true; + } + + /** + * Check if any token kind given as argument is found. + * + * @param list<_PhpTokenKind> $tokenKinds + */ + public function isAnyTokenKindsFound(array $tokenKinds): bool + { + foreach ($tokenKinds as $tokenKind) { + if (0 !== ($this->foundTokenKinds[$tokenKind] ?? 0)) { + return true; + } + } + + return false; + } + + /** + * Check if token kind given as argument is found. + * + * @param _PhpTokenKind $tokenKind + */ + public function isTokenKindFound($tokenKind): bool + { + return 0 !== ($this->foundTokenKinds[$tokenKind] ?? 0); + } + + /** + * @param _PhpTokenKind $tokenKind + */ + public function countTokenKind($tokenKind): int + { + return $this->foundTokenKinds[$tokenKind] ?? 0; + } + + /** + * Clear tokens in the given range. + */ + public function clearRange(int $indexStart, int $indexEnd): void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $this->clearAt($i); + } + } + + /** + * Checks for monolithic PHP code. + * + * Checks that the code is pure PHP code, in a single code block, starting + * with an open tag. + */ + public function isMonolithicPhp(): bool + { + if (1 !== ($this->countTokenKind(\T_OPEN_TAG) + $this->countTokenKind(\T_OPEN_TAG_WITH_ECHO))) { + return false; + } + + return 0 === $this->countTokenKind(\T_INLINE_HTML) + || (1 === $this->countTokenKind(\T_INLINE_HTML) && Preg::match('/^#!.+$/', $this[0]->getContent())); + } + + /** + * @param int $start start index + * @param int $end end index + */ + public function isPartialCodeMultiline(int $start, int $end): bool + { + for ($i = $start; $i <= $end; ++$i) { + if (str_contains($this[$i]->getContent(), "\n")) { + return true; + } + } + + return false; + } + + public function hasAlternativeSyntax(): bool + { + return $this->isAnyTokenKindsFound([ + \T_ENDDECLARE, + \T_ENDFOR, + \T_ENDFOREACH, + \T_ENDIF, + \T_ENDSWITCH, + \T_ENDWHILE, + ]); + } + + public function clearTokenAndMergeSurroundingWhitespace(int $index): void + { + $count = \count($this); + $this->clearAt($index); + + if ($index === $count - 1) { + return; + } + + $nextIndex = $this->getNonEmptySibling($index, 1); + + if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) { + return; + } + + $prevIndex = $this->getNonEmptySibling($index, -1); + + if ($this[$prevIndex]->isWhitespace()) { + $this[$prevIndex] = new Token([\T_WHITESPACE, $this[$prevIndex]->getContent().$this[$nextIndex]->getContent()]); + } elseif ($this->isEmptyAt($prevIndex + 1)) { + $this[$prevIndex + 1] = new Token([\T_WHITESPACE, $this[$nextIndex]->getContent()]); + } + + $this->clearAt($nextIndex); + } + + /** + * @internal This is performance-related workaround for lack of proper DI, may be removed at some point + * + * @return list + */ + public function getNamespaceDeclarations(): array + { + if (null === $this->namespaceDeclarations) { + $this->namespaceDeclarations = (new NamespacesAnalyzer())->getDeclarations($this); + } + + return $this->namespaceDeclarations; + } + + /** + * @internal + */ + protected function applyTransformers(): void + { + $transformers = Transformers::createSingleton(); + $transformers->transform($this); + } + + private function updateSizeByIncreasingToNewSize(int $size): void + { + $currentSize = \count($this); + if ($currentSize >= $size) { + throw new \LogicException(\sprintf('Cannot use called method to decrease collection size (%d -> %d).', $currentSize, $size)); + } + parent::setSize($size); + } + + private function updateSizeToZero(): void + { + $currentSize = \count($this); + if (0 === $currentSize) { + return; + } + + $this->changed = true; + $this->collectionHash = null; + self::clearCache($this->codeHash); + $this->codeHash = null; + $this->namespaceDeclarations = null; + $this->blockStartCache = []; + $this->blockEndCache = []; + + parent::setSize(0); + } + + private function updateSizeByTrimmingTrailingEmptyTokens(): void + { + $currentSize = \count($this); + + if (0 === $currentSize) { + return; + } + + $lastIndex = $currentSize - 1; + + while ($lastIndex >= 0 && $this->isEmptyAt($lastIndex)) { + --$lastIndex; + } + + parent::setSize($lastIndex + 1); + } + + /** + * @param -1|1 $direction + */ + private function removeWhitespaceSafely(int $index, int $direction, ?string $whitespaces = null): void + { + $whitespaceIndex = $this->getNonEmptySibling($index, $direction); + if (isset($this[$whitespaceIndex]) && $this[$whitespaceIndex]->isWhitespace()) { + $newContent = ''; + $tokenToCheck = $this[$whitespaceIndex]; + + // if the token candidate to remove is preceded by single line comment we do not consider the new line after this comment as part of T_WHITESPACE + if (isset($this[$whitespaceIndex - 1]) && $this[$whitespaceIndex - 1]->isComment() && !str_starts_with($this[$whitespaceIndex - 1]->getContent(), '/*')) { + [, $newContent, $whitespacesToCheck] = Preg::split('/^(\R)/', $this[$whitespaceIndex]->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE); + + if ('' === $whitespacesToCheck) { + return; + } + + $tokenToCheck = new Token([\T_WHITESPACE, $whitespacesToCheck]); + } + + if (!$tokenToCheck->isWhitespace($whitespaces)) { + return; + } + + if ('' === $newContent) { + $this->clearAt($whitespaceIndex); + } else { + $this[$whitespaceIndex] = new Token([\T_WHITESPACE, $newContent]); + } + } + } + + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of starting brace + * @param bool $findEnd if method should find block's end or start + * + * @return int<0, max> index of opposite brace + */ + private function findOppositeBlockEdge(int $type, int $searchIndex, bool $findEnd): int + { + $blockEdgeDefinitions = self::getBlockEdgeDefinitions(); + + if (!isset($blockEdgeDefinitions[$type])) { + throw new \InvalidArgumentException(\sprintf('Invalid param type: "%s".', $type)); + } + + if ($findEnd && isset($this->blockStartCache[$searchIndex])) { + \assert($this->blockStartCache[$searchIndex] >= 0); + + return $this->blockStartCache[$searchIndex]; + } + + if (!$findEnd && isset($this->blockEndCache[$searchIndex])) { + \assert($this->blockEndCache[$searchIndex] >= 0); + + return $this->blockEndCache[$searchIndex]; + } + + $startEdge = $blockEdgeDefinitions[$type]['start']; + $endEdge = $blockEdgeDefinitions[$type]['end']; + $startIndex = $searchIndex; + $endIndex = \count($this) - 1; + $indexOffset = 1; + + if (!$findEnd) { + [$startEdge, $endEdge] = [$endEdge, $startEdge]; + $indexOffset = -1; + $endIndex = 0; + } + + if (!$this[$startIndex]->equals($startEdge)) { + throw new \InvalidArgumentException(\sprintf('Invalid param $startIndex - not a proper block "%s".', $findEnd ? 'start' : 'end')); + } + + $blockLevel = 0; + + for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) { + $token = $this[$index]; + + if ($token->equals($startEdge)) { + ++$blockLevel; + + continue; + } + + if ($token->equals($endEdge)) { + --$blockLevel; + + if (0 === $blockLevel) { + break; + } + } + } + + if (!$this[$index]->equals($endEdge)) { + throw new \UnexpectedValueException(\sprintf('Missing block "%s".', $findEnd ? 'end' : 'start')); + } + + \assert($index >= 0 && $startIndex >= 0); + + if ($startIndex < $index) { + $this->blockStartCache[$startIndex] = $index; + $this->blockEndCache[$index] = $startIndex; + } else { + $this->blockStartCache[$index] = $startIndex; + $this->blockEndCache[$startIndex] = $index; + } + + return $index; + } + + /** + * @return non-empty-string + */ + private static function calculateHash(string $code): string + { + return Hasher::calculate($code); + } + + /** + * Get cache value for given key. + * + * @param non-empty-string $key item key + */ + private static function getCache(string $key): self + { + if (!self::hasCache($key)) { + throw new \OutOfBoundsException(\sprintf('Unknown cache key: "%s".', $key)); + } + + \assert(isset(self::$cache[$key])); + + return self::$cache[$key]; + } + + /** + * Check if given key exists in cache. + * + * @param non-empty-string $key item key + */ + private static function hasCache(string $key): bool + { + return isset(self::$cache[$key]); + } + + /** + * @param non-empty-string $key item key + * @param Tokens $value item value + */ + private static function setCache(string $key, self $value): void + { + self::$cache[$key] = $value; + } + + /** + * Change code hash. + * + * Remove old cache and set new one. + * + * @param non-empty-string $codeHash new code hash + */ + private function changeCodeHash(string $codeHash): void + { + if (null !== $this->codeHash) { + self::clearCache($this->codeHash); + } + + $this->codeHash = $codeHash; + self::setCache($this->codeHash, $this); + } + + /** + * Register token as found. + */ + private function registerFoundToken(Token $token): void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token->isArray() ? $token->getId() : $token->getContent(); + + $this->foundTokenKinds[$tokenKind] ??= 0; + ++$this->foundTokenKinds[$tokenKind]; + } + + /** + * Unregister token as not found. + */ + private function unregisterFoundToken(Token $token): void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token->isArray() ? $token->getId() : $token->getContent(); + + \assert(($this->foundTokenKinds[$tokenKind] ?? 0) > 0); + --$this->foundTokenKinds[$tokenKind]; + } + + /** + * @param _PhpTokenPrototypePartial|Token $token token prototype + * + * @return _PhpTokenKind + */ + private function extractTokenKind($token) + { + return $token instanceof Token + ? ($token->isArray() ? $token->getId() : $token->getContent()) + : (\is_array($token) ? $token[0] : $token); + } + + /** + * @param int $index token index + * @param -1|1 $direction + * @param callable(int): bool $filter + */ + private function getTokenNotOfKind(int $index, int $direction, callable $filter): ?int + { + while (true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + + if ($this->isEmptyAt($index) || $filter($index)) { + continue; + } + + return $index; + } + } + + /** + * A helper method used to find out whether a certain input token has to be case-sensitively matched. + * + * @param array|bool $caseSensitive global case sensitiveness or an array of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * @param int $key the key of the token that has to be looked up + */ + private static function isKeyCaseSensitive($caseSensitive, int $key): bool + { + if (\is_array($caseSensitive)) { + return $caseSensitive[$key] ?? true; + } + + return $caseSensitive; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php new file mode 100644 index 0000000..3274c4a --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php @@ -0,0 +1,890 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; + +/** + * Analyzer of Tokens collection. + * + * Its role is to provide the ability to analyse collection. + * + * @internal + * + * @phpstan-type _ClassyElementType 'case'|'const'|'method'|'property'|'promoted_property'|'trait_import' + * + * @author Dariusz Rumiński + * @author Gregor Harlan + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TokensAnalyzer +{ + /** + * Tokens collection instance. + */ + private Tokens $tokens; + + /** + * @readonly + */ + private GotoLabelAnalyzer $gotoLabelAnalyzer; + + public function __construct(Tokens $tokens) + { + $this->tokens = $tokens; + $this->gotoLabelAnalyzer = new GotoLabelAnalyzer(); + } + + /** + * Get indices of methods and properties in classy code (classes, interfaces and traits). + * + * @return array + */ + public function getClassyElements(): array + { + $elements = []; + + for ($index = 1, $count = \count($this->tokens) - 2; $index < $count; ++$index) { + if ($this->tokens[$index]->isClassy()) { + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + + ksort($elements); + + return $elements; + } + + /** + * Get indices of modifiers of a classy code (classes, interfaces and traits). + * + * @return array{ + * final: null|int, + * abstract: null|int, + * readonly: null|int + * } + */ + public function getClassyModifiers(int $index): array + { + if (!$this->tokens[$index]->isClassy()) { + throw new \InvalidArgumentException(\sprintf('Not an "classy" at given index %d.', $index)); + } + + $modifiers = ['final' => null, 'abstract' => null, 'readonly' => null]; + + while (true) { + $index = $this->tokens->getPrevMeaningfulToken($index); + + if ($this->tokens[$index]->isGivenKind(\T_FINAL)) { + $modifiers['final'] = $index; + } elseif ($this->tokens[$index]->isGivenKind(\T_ABSTRACT)) { + $modifiers['abstract'] = $index; + } elseif ($this->tokens[$index]->isGivenKind(FCT::T_READONLY)) { + $modifiers['readonly'] = $index; + } else { // no need to skip attributes as it is not possible on PHP8.2 + break; + } + } + + return $modifiers; + } + + /** + * Get indices of namespace uses. + * + * @param bool $perNamespace Return namespace uses per namespace + * + * @return ($perNamespace is true ? array> : list) + */ + public function getImportUseIndexes(bool $perNamespace = false): array + { + $tokens = $this->tokens; + + $uses = []; + $namespaceIndex = 0; + + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_NAMESPACE)) { + $nextTokenIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + $nextToken = $tokens[$nextTokenIndex]; + + if ($nextToken->equals('{')) { + $index = $nextTokenIndex; + } + + if ($perNamespace) { + ++$namespaceIndex; + } + + continue; + } + + if ($token->isGivenKind(\T_USE)) { + $uses[$namespaceIndex][] = $index; + } + } + + if (!$perNamespace && isset($uses[$namespaceIndex])) { + return $uses[$namespaceIndex]; + } + + return $uses; + } + + /** + * Check if there is an array at given index. + */ + public function isArray(int $index): bool + { + return $this->tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_BRACKET_OPEN]); + } + + /** + * Check if the array at index is multiline. + * + * This only checks the root-level of the array. + */ + public function isArrayMultiLine(int $index): bool + { + if (!$this->isArray($index)) { + throw new \InvalidArgumentException(\sprintf('Not an array at given index %d.', $index)); + } + + $tokens = $this->tokens; + + // Skip only when it's an array, for short arrays we need the brace for correct + // level counting + if ($tokens[$index]->isGivenKind(\T_ARRAY)) { + $index = $tokens->getNextMeaningfulToken($index); + } + + return $this->isBlockMultiline($tokens, $index); + } + + public function isBlockMultiline(Tokens $tokens, int $index): bool + { + $blockType = Tokens::detectBlockType($tokens[$index]); + + if (null === $blockType || !$blockType['isStart']) { + throw new \InvalidArgumentException(\sprintf('Not an block start at given index %d.', $index)); + } + + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + + for (++$index; $index < $endIndex; ++$index) { + $token = $tokens[$index]; + $blockType = Tokens::detectBlockType($token); + + if (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + if ( + $token->isWhitespace() + && !$tokens[$index - 1]->isGivenKind(\T_END_HEREDOC) + && str_contains($token->getContent(), "\n") + ) { + return true; + } + } + + return false; + } + + /** + * @param int $index Index of the T_FUNCTION token + * + * @return array{visibility: null|T_PRIVATE|T_PROTECTED|T_PUBLIC, static: bool, abstract: bool, final: bool} + */ + public function getMethodAttributes(int $index): array + { + if (!$this->tokens[$index]->isGivenKind(\T_FUNCTION)) { + throw new \LogicException(\sprintf('No T_FUNCTION at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $attributes = [ + 'visibility' => null, + 'static' => false, + 'abstract' => false, + 'final' => false, + ]; + + for ($i = $index; $i >= 0; --$i) { + $i = $this->tokens->getPrevMeaningfulToken($i); + $token = $this->tokens[$i]; + + if ($token->isGivenKind(\T_STATIC)) { + $attributes['static'] = true; + + continue; + } + + if ($token->isGivenKind(\T_FINAL)) { + $attributes['final'] = true; + + continue; + } + + if ($token->isGivenKind(\T_ABSTRACT)) { + $attributes['abstract'] = true; + + continue; + } + + // visibility + + if ($token->isGivenKind(\T_PRIVATE)) { + $attributes['visibility'] = \T_PRIVATE; + + continue; + } + + if ($token->isGivenKind(\T_PROTECTED)) { + $attributes['visibility'] = \T_PROTECTED; + + continue; + } + + if ($token->isGivenKind(\T_PUBLIC)) { + $attributes['visibility'] = \T_PUBLIC; + + continue; + } + + // found a meaningful token that is not part of + // the function signature; stop looking + break; + } + + return $attributes; + } + + /** + * Check if there is an anonymous class under given index. + */ + public function isAnonymousClass(int $index): bool + { + if (!$this->tokens[$index]->isClassy()) { + throw new \LogicException(\sprintf('No classy token at given index %d.', $index)); + } + + if (!$this->tokens[$index]->isGivenKind(\T_CLASS)) { + return false; + } + + $index = $this->tokens->getPrevMeaningfulToken($index); + + if ($this->tokens[$index]->isGivenKind(FCT::T_READONLY)) { + $index = $this->tokens->getPrevMeaningfulToken($index); + } + + while ($this->tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $this->tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $this->tokens->getPrevMeaningfulToken($index); + } + + return $this->tokens[$index]->isGivenKind(\T_NEW); + } + + /** + * Check if the function under given index is a lambda. + */ + public function isLambda(int $index): bool + { + if (!$this->tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { + throw new \LogicException(\sprintf('No T_FUNCTION or T_FN at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($index); + $startParenthesisToken = $this->tokens[$startParenthesisIndex]; + + // skip & for `function & () {}` syntax + if ($startParenthesisToken->isGivenKind(CT::T_RETURN_REF)) { + $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex); + $startParenthesisToken = $this->tokens[$startParenthesisIndex]; + } + + return $startParenthesisToken->equals('('); + } + + public function getLastTokenIndexOfArrowFunction(int $index): int + { + if (!$this->tokens[$index]->isGivenKind(\T_FN)) { + throw new \InvalidArgumentException(\sprintf('Not an "arrow function" at given index %d.', $index)); + } + + $stopTokens = [')', ']', ',', ';', [\T_CLOSE_TAG]]; + $index = $this->tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); + + while (true) { + $index = $this->tokens->getNextMeaningfulToken($index); + + if ($this->tokens[$index]->equalsAny($stopTokens)) { + break; + } + + $blockType = Tokens::detectBlockType($this->tokens[$index]); + + if (null === $blockType) { + continue; + } + + if ($blockType['isStart']) { + $index = $this->tokens->findBlockEnd($blockType['type'], $index); + + continue; + } + + break; + } + + return $this->tokens->getPrevMeaningfulToken($index); + } + + /** + * Check if the T_STRING under given index is a constant invocation. + */ + public function isConstantInvocation(int $index): bool + { + if (!$this->tokens[$index]->isGivenKind(\T_STRING)) { + throw new \LogicException(\sprintf('No T_STRING at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + + $nextIndex = $this->tokens->getNextMeaningfulToken($index); + + if ( + $this->tokens[$nextIndex]->equalsAny(['(', '{']) + || $this->tokens[$nextIndex]->isGivenKind([\T_DOUBLE_COLON, \T_ELLIPSIS, \T_NS_SEPARATOR, CT::T_RETURN_REF, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_VARIABLE]) + ) { + return false; + } + + // handle foreach( FOO as $_ ) {} + if ($this->tokens[$nextIndex]->isGivenKind(\T_AS)) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($index); + + if (!$this->tokens[$prevIndex]->equals('(')) { + return false; + } + } + + $prevIndex = $this->tokens->getPrevMeaningfulToken($index); + + if ($this->tokens[$prevIndex]->isGivenKind(Token::getClassyTokenKinds())) { + return false; + } + + if ($this->tokens[$prevIndex]->isGivenKind([\T_AS, \T_CONST, \T_DOUBLE_COLON, \T_FUNCTION, \T_GOTO, CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_TYPE_COLON, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]) || $this->tokens[$prevIndex]->isObjectOperator()) { + return false; + } + + if ( + $this->tokens[$prevIndex]->isGivenKind(\T_CASE) + && $this->tokens->isAllTokenKindsFound([FCT::T_ENUM]) + ) { + $enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[\T_SWITCH], [\T_ENUM]]); + + if (!$this->tokens[$enumSwitchIndex]->isGivenKind(\T_SWITCH)) { + return false; + } + } + + while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING, CT::T_ARRAY_TYPEHINT])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + + if ($this->tokens[$prevIndex]->isGivenKind([CT::T_CONST_IMPORT, \T_EXTENDS, CT::T_FUNCTION_IMPORT, \T_IMPLEMENTS, \T_INSTANCEOF, \T_INSTEADOF, \T_NAMESPACE, \T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, \T_USE, CT::T_USE_TRAIT, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION, \T_CONST, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])) { + return false; + } + + // `FOO & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = FOO & $bar; + if ($this->tokens[$nextIndex]->equals('&') && $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(\T_VARIABLE)) { + $checkIndex = $this->tokens->getPrevTokenOfKind($prevIndex, [';', '{', '}', [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]]); + + if ($this->tokens[$checkIndex]->isGivenKind(\T_FUNCTION)) { + return false; + } + } + + // check for `extends`/`implements`/`use` list + if ($this->tokens[$prevIndex]->equals(',')) { + $checkIndex = $prevIndex; + + while ($this->tokens[$checkIndex]->equalsAny([',', [\T_AS], [CT::T_NAMESPACE_OPERATOR], [\T_NS_SEPARATOR], [\T_STRING]])) { + $checkIndex = $this->tokens->getPrevMeaningfulToken($checkIndex); + } + + if ($this->tokens[$checkIndex]->isGivenKind([\T_EXTENDS, CT::T_GROUP_IMPORT_BRACE_OPEN, \T_IMPLEMENTS, \T_USE, CT::T_USE_TRAIT])) { + return false; + } + } + + // check for array in double quoted string: `"..$foo[bar].."` + if ($this->tokens[$prevIndex]->equals('[') && $this->tokens[$nextIndex]->equals(']')) { + $checkToken = $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]; + + if ($checkToken->equals('"') || $checkToken->isGivenKind([\T_CURLY_OPEN, \T_DOLLAR_OPEN_CURLY_BRACES, \T_ENCAPSED_AND_WHITESPACE, \T_VARIABLE])) { + return false; + } + } + + // check for attribute: `#[Foo]` + if (AttributeAnalyzer::isAttribute($this->tokens, $index)) { + return false; + } + + // check for goto label + if ($this->tokens[$nextIndex]->equals(':')) { + if ($this->gotoLabelAnalyzer->belongsToGoToLabel($this->tokens, $nextIndex)) { + return false; + } + } + + // check for non-capturing catches + + while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING, CT::T_TYPE_ALTERNATION])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + + if ($this->tokens[$prevIndex]->equals('(')) { + $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + + if ($this->tokens[$prevPrevIndex]->isGivenKind(\T_CATCH)) { + return false; + } + } + + return true; + } + + /** + * Checks if there is a unary successor operator under given index. + */ + public function isUnarySuccessorOperator(int $index): bool + { + $tokens = $this->tokens; + $token = $tokens[$index]; + + if (!$token->isGivenKind([\T_INC, \T_DEC])) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + return $prevToken->equalsAny([ + ']', + [\T_STRING], + [\T_VARIABLE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + ]); + } + + /** + * Checks if there is a unary predecessor operator under given index. + */ + public function isUnaryPredecessorOperator(int $index): bool + { + $tokens = $this->tokens; + $token = $tokens[$index]; + + // potential unary successor operator + if ($token->isGivenKind([\T_INC, \T_DEC])) { + return !$this->isUnarySuccessorOperator($index); + } + + // always unary predecessor operator + if ($token->equalsAny(['!', '~', '@', [\T_ELLIPSIS]])) { + return true; + } + + // potential binary operator + if (!$token->equalsAny(['+', '-', '&', [CT::T_RETURN_REF]])) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->equalsAny([ + ']', + '}', + ')', + '"', + '`', + [CT::T_ARRAY_BRACKET_CLOSE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [\T_CLASS_C], + [\T_CONSTANT_ENCAPSED_STRING], + [\T_DEC], + [\T_DIR], + [\T_DNUMBER], + [\T_FILE], + [\T_FUNC_C], + [\T_INC], + [\T_LINE], + [\T_LNUMBER], + [\T_METHOD_C], + [\T_NS_C], + [\T_STRING], + [\T_TRAIT_C], + [\T_VARIABLE], + ])) { + return true; + } + + if (!$token->equals('&') || !$prevToken->isGivenKind(\T_STRING)) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevTokenOfKind($index, [ + ';', + '{', + '}', + [\T_DOUBLE_ARROW], + [\T_FN], + [\T_FUNCTION], + [\T_OPEN_TAG], + [\T_OPEN_TAG_WITH_ECHO], + ])]; + + return $prevToken->isGivenKind([\T_FN, \T_FUNCTION]); + } + + /** + * Checks if there is a binary operator under given index. + */ + public function isBinaryOperator(int $index): bool + { + $tokens = $this->tokens; + $token = $tokens[$index]; + + if ($token->isGivenKind([\T_INLINE_HTML, \T_ENCAPSED_AND_WHITESPACE, CT::T_TYPE_INTERSECTION])) { + return false; + } + + // potential unary predecessor operator + if (\in_array($token->getContent(), ['+', '-', '&'], true)) { + return !$this->isUnaryPredecessorOperator($index); + } + + if ($token->isArray()) { + return \in_array($token->getId(), [ + \T_AND_EQUAL, // &= + \T_BOOLEAN_AND, // && + \T_BOOLEAN_OR, // || + \T_CONCAT_EQUAL, // .= + \T_DIV_EQUAL, // /= + \T_DOUBLE_ARROW, // => + \T_IS_EQUAL, // == + \T_IS_GREATER_OR_EQUAL, // >= + \T_IS_IDENTICAL, // === + \T_IS_NOT_EQUAL, // !=, <> + \T_IS_NOT_IDENTICAL, // !== + \T_IS_SMALLER_OR_EQUAL, // <= + \T_LOGICAL_AND, // and + \T_LOGICAL_OR, // or + \T_LOGICAL_XOR, // xor + \T_MINUS_EQUAL, // -= + \T_MOD_EQUAL, // %= + \T_MUL_EQUAL, // *= + \T_OR_EQUAL, // |= + \T_PLUS_EQUAL, // += + \T_POW, // ** + \T_POW_EQUAL, // **= + \T_SL, // << + \T_SL_EQUAL, // <<= + \T_SR, // >> + \T_SR_EQUAL, // >>= + \T_XOR_EQUAL, // ^= + \T_SPACESHIP, // <=> + \T_COALESCE, // ?? + \T_COALESCE_EQUAL, // ??= + ], true); + } + + if (\in_array($token->getContent(), ['=', '*', '/', '%', '<', '>', '|', '^', '.'], true)) { + return true; + } + + return false; + } + + /** + * Check if `T_WHILE` token at given index is `do { ... } while ();` syntax + * and not `while () { ...}`. + */ + public function isWhilePartOfDoWhile(int $index): bool + { + $tokens = $this->tokens; + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_WHILE)) { + throw new \LogicException(\sprintf('No T_WHILE at given index %d, got "%s".', $index, $token->getName())); + } + + $endIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$endIndex]->equals('}')) { + return false; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $endIndex); + $beforeStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + + return $tokens[$beforeStartIndex]->isGivenKind(\T_DO); + } + + /** + * @throws \LogicException when provided index does not point to token containing T_CASE + */ + public function isEnumCase(int $caseIndex): bool + { + $tokens = $this->tokens; + $token = $tokens[$caseIndex]; + + if (!$token->isGivenKind(\T_CASE)) { + throw new \LogicException(\sprintf( + 'No T_CASE given at index %d, got %s instead.', + $caseIndex, + $token->getName() ?? $token->getContent(), + )); + } + + if (!$tokens->isTokenKindFound(FCT::T_ENUM)) { + return false; + } + + $prevIndex = $caseIndex; + + // get the T_ENUM or T_SWITCH that is matching the T_CASE, detecting and skipping the {...} blocks in between, as they may have nested switch-case + while (true) { + $prevIndex = $tokens->getPrevTokenOfKind($prevIndex, ['}', [\T_ENUM], [\T_SWITCH]]); + \assert(null !== $prevIndex); + + if ($tokens[$prevIndex]->equals('}')) { + $prevIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $prevIndex); + } else { + break; + } + } + + return $tokens[$prevIndex]->isGivenKind(\T_ENUM); + } + + public function isSuperGlobal(int $index): bool + { + $token = $this->tokens[$index]; + + if (!$token->isGivenKind(\T_VARIABLE)) { + return false; + } + + return \in_array(strtoupper($token->getContent()), [ + '$_COOKIE', + '$_ENV', + '$_FILES', + '$_GET', + '$_POST', + '$_REQUEST', + '$_SERVER', + '$_SESSION', + '$GLOBALS', + ], true); + } + + /** + * Find classy elements. + * + * Searches in tokens from the classy (start) index till the end (index) of the classy. + * Returns an array; first value is the index until the method has analysed (int), second the found classy elements (array). + * + * @param int $classIndex classy index + * + * @return array{int, array} + */ + private function findClassyElements(int $classIndex, int $index): array + { + $elements = []; + $curlyBracesLevel = 0; + $bracesLevel = 0; + ++$index; // skip the classy index itself + + for ($count = \count($this->tokens); $index < $count; ++$index) { + $token = $this->tokens[$index]; + + if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + continue; + } + + if ($token->isGivenKind(\T_CLASS)) { // anonymous class in class + // check for nested anonymous classes inside the new call of an anonymous class, + // for example `new class(function (){new class(function (){new class(function (){}){};}){};}){};` etc. + // if class(XYZ) {} skip till `(` as XYZ might contain functions etc. + + $nestedClassIndex = $index; + $index = $this->tokens->getNextMeaningfulToken($index); + + if ($this->tokens[$index]->equals('(')) { + ++$index; // move after `(` + + for ($nestedBracesLevel = 1; $index < $count; ++$index) { + $token = $this->tokens[$index]; + + if ($token->equals('(')) { + ++$nestedBracesLevel; + + continue; + } + + if ($token->equals(')')) { + --$nestedBracesLevel; + + if (0 === $nestedBracesLevel) { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $index); + $elements += $newElements; + + break; + } + + continue; + } + + if ($token->isGivenKind(\T_CLASS)) { // anonymous class in class + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + } else { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $nestedClassIndex); + $elements += $newElements; + } + + continue; + } + + if ($token->equals('(')) { + ++$bracesLevel; + + continue; + } + + if ($token->equals(')')) { + --$bracesLevel; + + continue; + } + + if ($token->equals('{')) { + ++$curlyBracesLevel; + + continue; + } + + if ($token->equals('}')) { + --$curlyBracesLevel; + + if (0 === $curlyBracesLevel) { + break; + } + + continue; + } + + if (1 !== $curlyBracesLevel || !$token->isArray()) { + continue; + } + + if (0 === $bracesLevel && $token->isGivenKind(\T_VARIABLE)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'property', + ]; + + continue; + } + + if ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { + $index = $this->tokens->getNextTokenOfKind($index, [[CT::T_PROPERTY_HOOK_BRACE_CLOSE]]); + + continue; + } + + if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { + $index = $this->tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + + continue; + } + + if ($token->isGivenKind(\T_FUNCTION)) { + $functionNameIndex = $this->tokens->getNextMeaningfulToken($index); + if ($this->tokens[$functionNameIndex]->equals('(')) { + continue; + } + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'method', + ]; + if ('__construct' === $this->tokens[$functionNameIndex]->getContent()) { + $openParenthesis = $this->tokens->getNextMeaningfulToken($functionNameIndex); + $closeParenthesis = $this->tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis); + foreach ($this->tokens->findGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET, FCT::T_READONLY, \T_FINAL], $openParenthesis, $closeParenthesis) as $kindElements) { + foreach (array_keys($kindElements) as $promotedPropertyModifierIndex) { + /** @var int $promotedPropertyVariableIndex */ + $promotedPropertyVariableIndex = $this->tokens->getNextTokenOfKind($promotedPropertyModifierIndex, [[\T_VARIABLE]]); + $elements[$promotedPropertyVariableIndex] = [ + 'classIndex' => $classIndex, + 'token' => $this->tokens[$promotedPropertyVariableIndex], + 'type' => 'promoted_property', + ]; + } + } + } + } elseif ($token->isGivenKind(\T_CONST)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'const', + ]; + } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'trait_import', + ]; + } elseif ($token->isGivenKind(\T_CASE)) { + $elements[$index] = [ + 'classIndex' => $classIndex, + 'token' => $token, + 'type' => 'case', + ]; + } + } + + return [$index, $elements]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php new file mode 100644 index 0000000..37ee3ab --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `array` typehint from T_ARRAY into CT::T_ARRAY_TYPEHINT. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ArrayTypehintTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind(\T_ARRAY)) { + return; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + $nextToken = $tokens[$nextIndex]; + + if (!$nextToken->equals('(')) { + $tokens[$index] = new Token([CT::T_ARRAY_TYPEHINT, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_ARRAY_TYPEHINT]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php new file mode 100644 index 0000000..acc0412 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transforms attribute related Tokens. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class AttributeTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run before all other transformers that might touch attributes + return 200; + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { + return; + } + + do { + ++$index; + + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index) + 1; + } + } while (!$tokens[$index]->equals(']')); + + $tokens[$index] = new Token([CT::T_ATTRIBUTE_CLOSE, ']']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_ATTRIBUTE_CLOSE, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php new file mode 100644 index 0000000..5f8f1be --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform braced class instantiation braces in `(new Foo())` into CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN + * and CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE. + * + * @author Sebastiaan Stok + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BraceClassInstantiationTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run after CurlyBraceTransformer and SquareBraceTransformer + return -2; + } + + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->equals('(') || !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_NEW)) { + return; + } + + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny([ + ')', + ']', + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + [CT::T_ARRAY_BRACKET_CLOSE], + [CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE], + [\T_ARRAY], + [\T_CLASS], + [\T_ELSEIF], + [\T_FOR], + [\T_FOREACH], + [\T_IF], + [\T_STATIC], + [\T_STRING], + [\T_SWITCH], + [\T_VARIABLE], + [\T_WHILE], + ])) { + return; + } + + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + + $tokens[$index] = new Token([CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN, '(']); + $tokens[$closeIndex] = new Token([CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE, ')']); + } + + public function getCustomTokens(): array + { + return [CT::T_CLASS_INSTANTIATION_PARENTHESIS_OPEN, CT::T_CLASS_INSTANTIATION_PARENTHESIS_CLOSE]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php new file mode 100644 index 0000000..8b93b85 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceTransformer.php @@ -0,0 +1,363 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform discriminate overloaded curly braces tokens. + * + * Performed transformations: + * - closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE, + * - closing `}` for T_DOLLAR_OPEN_CURLY_BRACES into CT::T_DOLLAR_CLOSE_CURLY_BRACES, + * - in `$foo->{$bar}` into CT::T_DYNAMIC_PROP_BRACE_OPEN and CT::T_DYNAMIC_PROP_BRACE_CLOSE, + * - in `${$foo}` into CT::T_DYNAMIC_VAR_BRACE_OPEN and CT::T_DYNAMIC_VAR_BRACE_CLOSE, + * - in `$array{$index}` into CT::T_ARRAY_INDEX_BRACE_OPEN and CT::T_ARRAY_INDEX_BRACE_CLOSE, + * - in `use some\a\{ClassA, ClassB, ClassC as C}` into CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_GROUP_IMPORT_BRACE_CLOSE, + * - in `class PropertyHooks { public string $bar _{_ set(string $value) { } _}_` into CT::T_PROPERTY_HOOK_BRACE_OPEN, CT::T_PROPERTY_HOOK_BRACE_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class BraceTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->transformIntoCurlyCloseBrace($tokens, $index); + $this->transformIntoDollarCloseBrace($tokens, $index); + $this->transformIntoDynamicPropBraces($tokens, $index); + $this->transformIntoDynamicVarBraces($tokens, $index); + $this->transformIntoPropertyHookBraces($tokens, $index); + $this->transformIntoCurlyIndexBraces($tokens, $index); + $this->transformIntoGroupUseBraces($tokens, $index); + $this->transformIntoDynamicClassConstantFetchBraces($tokens, $index); + } + + public function getCustomTokens(): array + { + return [ + CT::T_CURLY_CLOSE, + CT::T_DOLLAR_CLOSE_CURLY_BRACES, + CT::T_DYNAMIC_PROP_BRACE_OPEN, + CT::T_DYNAMIC_PROP_BRACE_CLOSE, + CT::T_DYNAMIC_VAR_BRACE_OPEN, + CT::T_DYNAMIC_VAR_BRACE_CLOSE, + CT::T_ARRAY_INDEX_BRACE_OPEN, + CT::T_ARRAY_INDEX_BRACE_CLOSE, + CT::T_GROUP_IMPORT_BRACE_OPEN, + CT::T_GROUP_IMPORT_BRACE_CLOSE, + CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN, + CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE, + CT::T_PROPERTY_HOOK_BRACE_OPEN, + CT::T_PROPERTY_HOOK_BRACE_CLOSE, + ]; + } + + /** + * Transform closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE. + * + * This should be done at very beginning of curly braces transformations. + */ + private function transformIntoCurlyCloseBrace(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->isGivenKind(\T_CURLY_OPEN)) { + return; + } + + $level = 1; + + do { + ++$index; + + if ($tokens[$index]->equals('{') || $tokens[$index]->isGivenKind(\T_CURLY_OPEN)) { // we count all kind of { + ++$level; + } elseif ($tokens[$index]->equals('}')) { // we count all kind of } + --$level; + } + } while (0 < $level); + + $tokens[$index] = new Token([CT::T_CURLY_CLOSE, '}']); + } + + private function transformIntoDollarCloseBrace(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if ($token->isGivenKind(\T_DOLLAR_OPEN_CURLY_BRACES)) { + $nextIndex = $tokens->getNextTokenOfKind($index, ['}']); + $tokens[$nextIndex] = new Token([CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}']); + } + } + + private function transformIntoDynamicPropBraces(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->isObjectOperator()) { + return; + } + + if (!$tokens[$index + 1]->equals('{')) { + return; + } + + $openIndex = $index + 1; + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}']); + } + + private function transformIntoDynamicVarBraces(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->equals('$')) { + return; + } + + $openIndex = $tokens->getNextMeaningfulToken($index); + + if (null === $openIndex) { + return; + } + + $openToken = $tokens[$openIndex]; + + if (!$openToken->equals('{')) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); + + $tokens[$openIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}']); + } + + private function transformIntoPropertyHookBraces(Tokens $tokens, int $index): void + { + if (\PHP_VERSION_ID < 8_04_00) { + return; // @TODO: drop condition when PHP 8.4+ is required or majority of the users are using 8.4+ + } + + $token = $tokens[$index]; + + if (!$token->equals('{')) { + return; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + // skip attributes + while ($tokens[$nextIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { + $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + + if (!$tokens[$nextIndex]->equalsAny([ + [\T_STRING, 'get'], + [\T_STRING, 'set'], + ], false)) { + return; + } + + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + + if (!$tokens[$nextNextIndex]->equalsAny(['(', '{', ';', [\T_DOUBLE_ARROW]])) { + return; + } + + if ($tokens[$nextNextIndex]->equals('(')) { + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $nextNextIndex); + $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); + if (!$tokens[$afterCloseParenthesisIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]])) { + return; + } + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + + $tokens[$index] = new Token([CT::T_PROPERTY_HOOK_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_PROPERTY_HOOK_BRACE_CLOSE, '}']); + } + + private function transformIntoCurlyIndexBraces(Tokens $tokens, int $index): void + { + // Support for fetching array index with braces syntax (`$arr{$index}`) + // was deprecated in 7.4 and removed in 8.0. However, the PHP's behaviour + // differs between 8.0-8.3 (fatal error in runtime) and 8.4 (parse error). + // + // @TODO Do not replace `CT::T_ARRAY_INDEX_CURLY_BRACE_*` for 8.0-8.3, as further optimization + if (\PHP_VERSION_ID >= 8_04_00) { + return; + } + + $token = $tokens[$index]; + + if (!$token->equals('{')) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevIndex]->equalsAny([ + [\T_STRING], + [\T_VARIABLE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + ']', + ')', + ])) { + return; + } + + if ( + $tokens[$prevIndex]->isGivenKind(\T_STRING) + && !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isObjectOperator() + ) { + return; + } + + if ( + $tokens[$prevIndex]->equals(')') + && !$tokens[$tokens->getPrevMeaningfulToken( + $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $prevIndex), + )]->isGivenKind(\T_ARRAY) + ) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + + $tokens[$index] = new Token([CT::T_ARRAY_INDEX_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_ARRAY_INDEX_BRACE_CLOSE, '}']); + } + + private function transformIntoGroupUseBraces(Tokens $tokens, int $index): void + { + $token = $tokens[$index]; + + if (!$token->equals('{')) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + return; + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + + $tokens[$index] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + } + + private function transformIntoDynamicClassConstantFetchBraces(Tokens $tokens, int $index): void + { + if (\PHP_VERSION_ID < 8_03_00) { + return; // @TODO: drop condition when PHP 8.3+ is required or majority of the users are using 8.3+ + } + + $token = $tokens[$index]; + + if (!$token->equals('{')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + + while (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_DOUBLE_COLON)) { + if (!$tokens[$prevMeaningfulTokenIndex]->equals(')')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + + if (!$tokens[$prevMeaningfulTokenIndex]->equals('}')) { + return; + } + + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_BRACE, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + } + + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + $nextMeaningfulTokenIndexAfterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + + if (!$tokens[$nextMeaningfulTokenIndexAfterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG], [\T_DOUBLE_COLON]])) { + return; + } + + $tokens[$index] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_BRACE_CLOSE, '}']); + } + + /** + * We do not want to rely on `$tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index)` here, + * as it relies on block types that are assuming that `}` tokens are already transformed to Custom Tokens that are allowing to distinguish different block types. + * As we are just about to transform `{` and `}` into Custom Tokens by this transformer, thus we need to compare those tokens manually by content without using `Tokens::findBlockEnd`. + */ + private function naivelyFindCurlyBlockEnd(Tokens $tokens, int $startIndex): int + { + if (!$tokens->offsetExists($startIndex)) { + throw new \OutOfBoundsException(\sprintf('Unavailable index: "%s".', $startIndex)); + } + + if ('{' !== $tokens[$startIndex]->getContent()) { + throw new \InvalidArgumentException(\sprintf('Wrong start index: "%s".', $startIndex)); + } + + $blockLevel = 1; + $endIndex = $tokens->count() - 1; + for ($index = $startIndex + 1; $index !== $endIndex; ++$index) { + $token = $tokens[$index]; + + if ('{' === $token->getContent()) { + ++$blockLevel; + + continue; + } + + if ('}' === $token->getContent()) { + --$blockLevel; + + if (0 === $blockLevel) { + if (!$token->equals('}')) { + throw new \UnexpectedValueException(\sprintf('Detected block end for index: "%s" was already transformed into other token type: "%s".', $startIndex, $token->getName())); + } + + return $index; + } + } + } + + throw new \UnexpectedValueException(\sprintf('Missing block end for index: "%s".', $startIndex)); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php new file mode 100644 index 0000000..91b33a2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `class` class' constant from T_CLASS into CT::T_CLASS_CONSTANT. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ClassConstantTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_05_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equalsAny([ + [\T_CLASS, 'class'], + [\T_STRING, 'class'], + ], false)) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + + if ($prevToken->isGivenKind(\T_DOUBLE_COLON)) { + $tokens[$index] = new Token([CT::T_CLASS_CONSTANT, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_CLASS_CONSTANT]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php new file mode 100644 index 0000000..5c44bb1 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transforms for Constructor Property Promotion. + * + * Transform T_PUBLIC, T_PROTECTED and T_PRIVATE of Constructor Property Promotion into custom tokens. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ConstructorPromotionTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + return; + } + + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + + if (!$tokens[$functionNameIndex]->isGivenKind(\T_STRING) || '__construct' !== strtolower($tokens[$functionNameIndex]->getContent())) { + return; + } + + /** @var int $openParenthesisIndex */ + $openParenthesisIndex = $tokens->getNextMeaningfulToken($functionNameIndex); // we are @ '(' now + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesisIndex); + + for ($argsIndex = $openParenthesisIndex; $argsIndex < $closeParenthesisIndex; ++$argsIndex) { + if ($tokens[$argsIndex]->isGivenKind(\T_PUBLIC)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, $tokens[$argsIndex]->getContent()]); + } elseif ($tokens[$argsIndex]->isGivenKind(\T_PROTECTED)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, $tokens[$argsIndex]->getContent()]); + } elseif ($tokens[$argsIndex]->isGivenKind(\T_PRIVATE)) { + $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, $tokens[$argsIndex]->getContent()]); + } + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, + CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php new file mode 100644 index 0000000..5e39121 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform DNF parentheses into CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN and CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE. + * + * @see https://wiki.php.net/rfc/dnf_types + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class DisjunctiveNormalFormTypeParenthesisTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after TypeAlternationTransformer + return -16; + } + + public function getRequiredPhpVersionId(): int + { + return 8_02_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $index; + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + } elseif ($token->equals(')') && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $index); + $closeIndex = $index; + } else { + return; + } + + $tokens[$openIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '(']); + $tokens[$closeIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, + CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php new file mode 100644 index 0000000..75cb857 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class FirstClassCallableTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 8_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ( + $token->isGivenKind(\T_ELLIPSIS) + && $tokens[$tokens->getPrevMeaningfulToken($index)]->equals('(') + && $tokens[$tokens->getNextMeaningfulToken($index)]->equals(')') + ) { + $tokens[$index] = new Token([CT::T_FIRST_CLASS_CALLABLE, '...']); + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_FIRST_CLASS_CALLABLE, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php new file mode 100644 index 0000000..304d753 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform const/function import tokens. + * + * Performed transformations: + * - T_CONST into CT::T_CONST_IMPORT + * - T_FUNCTION into CT::T_FUNCTION_IMPORT + * + * @author Gregor Harlan + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ImportTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // Should run after CurlyBraceTransformer and ReturnRefTransformer + return -1; + } + + public function getRequiredPhpVersionId(): int + { + return 5_06_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind([\T_CONST, \T_FUNCTION])) { + return; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + + if (!$prevToken->isGivenKind(\T_USE)) { + $nextToken = $tokens[$tokens->getNextTokenOfKind($index, ['=', '(', [CT::T_RETURN_REF], [CT::T_GROUP_IMPORT_BRACE_CLOSE]])]; + + if (!$nextToken->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + return; + } + } + + $tokens[$index] = new Token([ + $token->isGivenKind(\T_FUNCTION) ? CT::T_FUNCTION_IMPORT : CT::T_CONST_IMPORT, + $token->getContent(), + ]); + } + + public function getCustomTokens(): array + { + return [CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php new file mode 100644 index 0000000..7eabdd7 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Processor\ImportProcessor; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED and T_NAME_RELATIVE into T_NAMESPACE T_NS_SEPARATOR T_STRING. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NameQualifiedTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + return 1; // must run before NamespaceOperatorTransformer + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->isGivenKind([FCT::T_NAME_QUALIFIED, FCT::T_NAME_FULLY_QUALIFIED])) { + $this->transformQualified($tokens, $token, $index); + } elseif ($token->isGivenKind(FCT::T_NAME_RELATIVE)) { + $this->transformRelative($tokens, $token, $index); + } + } + + public function getCustomTokens(): array + { + return []; + } + + private function transformQualified(Tokens $tokens, Token $token, int $index): void + { + \assert('' !== $token->getContent()); + $newTokens = ImportProcessor::tokenizeName($token->getContent()); + + $tokens->overrideRange($index, $index, $newTokens); + } + + private function transformRelative(Tokens $tokens, Token $token, int $index): void + { + \assert('' !== $token->getContent()); + $newTokens = ImportProcessor::tokenizeName($token->getContent()); + $newTokens[0] = new Token([\T_NAMESPACE, 'namespace']); + + $tokens->overrideRange($index, $index, $newTokens); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php new file mode 100644 index 0000000..4078bf4 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform named argument tokens. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamedArgumentTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after TypeColonTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 8_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$tokens[$index]->equals(':')) { + return; + } + + $stringIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$stringIndex]->isGivenKind(\T_STRING)) { + return; + } + + $preStringIndex = $tokens->getPrevMeaningfulToken($stringIndex); + + // if equals any [';', '{', '}', [T_OPEN_TAG]] than it is a goto label + // if equals ')' than likely it is a type colon, but sure not a name argument + // if equals '?' than it is part of ternary statement + + if (!$tokens[$preStringIndex]->equalsAny([',', '('])) { + return; + } + + $tokens[$stringIndex] = new Token([CT::T_NAMED_ARGUMENT_NAME, $tokens[$stringIndex]->getContent()]); + $tokens[$index] = new Token([CT::T_NAMED_ARGUMENT_COLON, ':']); + } + + public function getCustomTokens(): array + { + return [ + CT::T_NAMED_ARGUMENT_COLON, + CT::T_NAMED_ARGUMENT_NAME, + ]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php new file mode 100644 index 0000000..484312f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `namespace` operator from T_NAMESPACE into CT::T_NAMESPACE_OPERATOR. + * + * @author Gregor Harlan + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NamespaceOperatorTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_03_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isGivenKind(\T_NAMESPACE)) { + return; + } + + $nextIndex = $tokens->getNextMeaningfulToken($index); + + if ($tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens[$index] = new Token([CT::T_NAMESPACE_OPERATOR, $token->getContent()]); + } + } + + public function getCustomTokens(): array + { + return [CT::T_NAMESPACE_OPERATOR]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php new file mode 100644 index 0000000..47465d6 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `?` operator into CT::T_NULLABLE_TYPE in `function foo(?Bar $b) {}`. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class NullableTypeTransformer extends AbstractTransformer +{ + private const TYPES = [ + '(', + ',', + [CT::T_TYPE_COLON], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED], + [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE], + [CT::T_ATTRIBUTE_CLOSE], + [\T_PRIVATE], + [\T_PROTECTED], + [\T_PUBLIC], + [\T_VAR], + [\T_STATIC], + [\T_CONST], + [\T_ABSTRACT], + [\T_FINAL], + [FCT::T_READONLY], + [FCT::T_PRIVATE_SET], + [FCT::T_PROTECTED_SET], + [FCT::T_PUBLIC_SET], + ]; + + public function getPriority(): int + { + // needs to run after TypeColonTransformer + return -20; + } + + public function getRequiredPhpVersionId(): int + { + return 7_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals('?')) { + return; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + + if (!$tokens[$prevIndex]->equalsAny(self::TYPES)) { + return; + } + + if ( + $tokens[$prevIndex]->isGivenKind(\T_STATIC) + && $tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(\T_INSTANCEOF) + ) { + return; + } + + $tokens[$index] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + + public function getCustomTokens(): array + { + return [CT::T_NULLABLE_TYPE]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php new file mode 100644 index 0000000..fc178a0 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `&` operator into CT::T_RETURN_REF in `function & foo() {}`. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ReturnRefTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->equals('&') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([\T_FUNCTION, \T_FN])) { + $tokens[$index] = new Token([CT::T_RETURN_REF, '&']); + } + } + + public function getCustomTokens(): array + { + return [CT::T_RETURN_REF]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php new file mode 100644 index 0000000..4d6b55d --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php @@ -0,0 +1,185 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform discriminate overloaded square braces tokens. + * + * Performed transformations: + * - in `[1, 2, 3]` into CT::T_ARRAY_BRACKET_OPEN and CT::T_ARRAY_BRACKET_CLOSE, + * - in `[$a, &$b, [$c]] = array(1, 2, array(3))` into CT::T_DESTRUCTURING_BRACKET_OPEN and CT::T_DESTRUCTURING_BRACKET_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class SquareBraceTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // must run after CurlyBraceTransformer and AttributeTransformer + return -1; + } + + public function getRequiredPhpVersionId(): int + { + // Short array syntax was introduced in PHP 5.4, but the fixer is smart + // enough to handle it even before 5.4. + // Same for array destructing syntax sugar `[` introduced in PHP 7.1. + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($this->isArrayDestructing($tokens, $index)) { + $this->transformIntoDestructuringSquareBrace($tokens, $index); + + return; + } + + if ($this->isShortArray($tokens, $index)) { + $this->transformIntoArraySquareBrace($tokens, $index); + } + } + + public function getCustomTokens(): array + { + return [ + CT::T_ARRAY_BRACKET_OPEN, + CT::T_ARRAY_BRACKET_CLOSE, + CT::T_DESTRUCTURING_BRACKET_OPEN, + CT::T_DESTRUCTURING_BRACKET_CLOSE, + ]; + } + + private function transformIntoArraySquareBrace(Tokens $tokens, int $index): void + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACKET, $index); + + $tokens[$index] = new Token([CT::T_ARRAY_BRACKET_OPEN, '[']); + $tokens[$endIndex] = new Token([CT::T_ARRAY_BRACKET_CLOSE, ']']); + } + + private function transformIntoDestructuringSquareBrace(Tokens $tokens, int $index): void + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACKET, $index); + + $tokens[$index] = new Token([CT::T_DESTRUCTURING_BRACKET_OPEN, '[']); + $tokens[$endIndex] = new Token([CT::T_DESTRUCTURING_BRACKET_CLOSE, ']']); + + $previousMeaningfulIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + + while ($index < $endIndex) { + if ($tokens[$index]->equals('[') && $tokens[$previousMeaningfulIndex]->equalsAny([[CT::T_DESTRUCTURING_BRACKET_OPEN], ','])) { + $tokens[$tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_BRACKET, $index)] = new Token([CT::T_DESTRUCTURING_BRACKET_CLOSE, ']']); + $tokens[$index] = new Token([CT::T_DESTRUCTURING_BRACKET_OPEN, '[']); + } + + $previousMeaningfulIndex = $index; + $index = $tokens->getNextMeaningfulToken($index); + } + } + + /** + * Check if token under given index is short array opening. + */ + private function isShortArray(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals('[')) { + return false; + } + + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + if ($prevToken->equalsAny([ + ')', + ']', + '}', + '"', + [\T_CONSTANT_ENCAPSED_STRING], + [\T_STRING], + [\T_STRING_VARNAME], + [\T_VARIABLE], + [CT::T_ARRAY_BRACKET_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + ])) { + return false; + } + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + if ($nextToken->equals(']')) { + return true; + } + + return !$this->isArrayDestructing($tokens, $index); + } + + private function isArrayDestructing(Tokens $tokens, int $index): bool + { + if (!$tokens[$index]->equals('[')) { + return false; + } + + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if ($prevToken->equalsAny([ + ')', + ']', + '"', + [\T_CONSTANT_ENCAPSED_STRING], + [\T_STRING], + [\T_STRING_VARNAME], + [\T_VARIABLE], + [CT::T_ARRAY_BRACKET_CLOSE], + [CT::T_DYNAMIC_PROP_BRACE_CLOSE], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_ARRAY_INDEX_BRACE_CLOSE], + ])) { + return false; + } + + if ($prevToken->isGivenKind(\T_AS)) { + return true; + } + + if ($prevToken->isGivenKind(\T_DOUBLE_ARROW)) { + $variableIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) { + return false; + } + + $prevVariableIndex = $tokens->getPrevMeaningfulToken($variableIndex); + if ($tokens[$prevVariableIndex]->isGivenKind(\T_AS)) { + return true; + } + } + + $type = Tokens::detectBlockType($tokens[$index]); + $end = $tokens->findBlockEnd($type['type'], $index); + + $nextToken = $tokens[$tokens->getNextMeaningfulToken($end)]; + + return $nextToken->equals('='); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php new file mode 100644 index 0000000..9bfaf95 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `|` operator into CT::T_TYPE_ALTERNATION in `function foo(Type1 | Type2 $x) {` + * or `} catch (ExceptionType1 | ExceptionType2 $e) {`. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeAlternationTransformer extends AbstractTypeTransformer +{ + public function getPriority(): int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 7_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->doProcess($tokens, $index, '|'); + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_ALTERNATION]; + } + + protected function replaceToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php new file mode 100644 index 0000000..7b9f342 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `:` operator into CT::T_TYPE_COLON in `function foo() : int {}`. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeColonTransformer extends AbstractTransformer +{ + public function getPriority(): int + { + // needs to run after ReturnRefTransformer and UseTransformer + // and before TypeAlternationTransformer + return -10; + } + + public function getRequiredPhpVersionId(): int + { + return 7_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->equals(':')) { + return; + } + + $endIndex = $tokens->getPrevMeaningfulToken($index); + + if ($tokens[$tokens->getPrevMeaningfulToken($endIndex)]->isGivenKind(FCT::T_ENUM)) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + + return; + } + + if (!$tokens[$endIndex]->equals(')')) { + return; + } + + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS, $endIndex); + $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); + $prevToken = $tokens[$prevIndex]; + + // if this could be a function name we need to take one more step + if ($prevToken->isGivenKind(\T_STRING)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + $prevToken = $tokens[$prevIndex]; + } + + if ($prevToken->isGivenKind([\T_FUNCTION, CT::T_RETURN_REF, CT::T_USE_LAMBDA, \T_FN])) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + } + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_COLON]; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php new file mode 100644 index 0000000..174736e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform `&` operator into CT::T_TYPE_INTERSECTION in `function foo(Type1 & Type2 $x) {` + * or `} catch (ExceptionType1 & ExceptionType2 $e) {`. + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class TypeIntersectionTransformer extends AbstractTypeTransformer +{ + public function getPriority(): int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + + public function getRequiredPhpVersionId(): int + { + return 8_01_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + $this->doProcess($tokens, $index, [\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']); + } + + public function getCustomTokens(): array + { + return [CT::T_TYPE_INTERSECTION]; + } + + protected function replaceToken(Tokens $tokens, int $index): void + { + $tokens[$index] = new Token([CT::T_TYPE_INTERSECTION, '&']); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php new file mode 100644 index 0000000..5f69b88 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\FCT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Transform T_USE into: + * - CT::T_USE_TRAIT for imports, + * - CT::T_USE_LAMBDA for lambda variable uses. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class UseTransformer extends AbstractTransformer +{ + private const CLASS_TYPES = [\T_TRAIT, FCT::T_ENUM]; + + public function getPriority(): int + { + // Should run after CurlyBraceTransformer and before TypeColonTransformer + return -5; + } + + public function getRequiredPhpVersionId(): int + { + return 5_03_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if ($token->isGivenKind(\T_USE) && $this->isUseForLambda($tokens, $index)) { + $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); + + return; + } + + // Only search inside class/trait body for `T_USE` for traits. + // Cannot import traits inside interfaces or anywhere else + + if ($token->isGivenKind(\T_CLASS)) { + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON)) { + return; + } + } elseif (!$token->isGivenKind(self::CLASS_TYPES)) { + return; + } + + $index = $tokens->getNextTokenOfKind($index, ['{']); + $innerLimit = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE, $index); + + while ($index < $innerLimit) { + $token = $tokens[++$index]; + + if (!$token->isGivenKind(\T_USE)) { + continue; + } + + if ($this->isUseForLambda($tokens, $index)) { + $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); + } else { + $tokens[$index] = new Token([CT::T_USE_TRAIT, $token->getContent()]); + } + } + } + + public function getCustomTokens(): array + { + return [CT::T_USE_TRAIT, CT::T_USE_LAMBDA]; + } + + /** + * Check if token under given index is `use` statement for lambda function. + */ + private function isUseForLambda(Tokens $tokens, int $index): bool + { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + + // test `function () use ($foo) {}` case + return $nextToken->equals('('); + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php new file mode 100644 index 0000000..b302464 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php @@ -0,0 +1,66 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; + +/** + * Move trailing whitespaces from comments and docs into following T_WHITESPACE token. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WhitespacyCommentTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId(): int + { + return 5_00_00; + } + + public function process(Tokens $tokens, Token $token, int $index): void + { + if (!$token->isComment()) { + return; + } + + $content = $token->getContent(); + $trimmedContent = rtrim($content); + + // nothing trimmed, nothing to do + if ($content === $trimmedContent) { + return; + } + + $whitespaces = substr($content, \strlen($trimmedContent)); + + $tokens[$index] = new Token([$token->getId(), $trimmedContent]); + + if (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, $whitespaces.$tokens[$index + 1]->getContent()]); + } else { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, $whitespaces])); + } + } + + public function getCustomTokens(): array + { + return []; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php new file mode 100644 index 0000000..d6eb95f --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +/** + * Interface for Transformer class. + * + * Transformer role is to register custom tokens and transform Tokens collection to use them. + * + * Custom token is a user defined token type and is used to separate different meaning of original token type. + * For example T_ARRAY is a token for both creating new array and typehinting a parameter. This two meaning should have two token types. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface TransformerInterface +{ + /** + * Get tokens created by Transformer. + * + * @return list + */ + public function getCustomTokens(): array; + + /** + * Return the name of the transformer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName(): string; + + /** + * Returns the priority of the transformer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority(): int; + + /** + * Return minimal required PHP version id to transform the code. + * + * Custom Token kinds from Transformers are always registered, but sometimes + * there is no need to analyse the Tokens if for sure we cannot find examined + * token kind, e.g. transforming `T_FUNCTION` in ` + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Tokenizer; + +use Symfony\Component\Finder\Finder; + +/** + * Collection of Transformer classes. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Transformers +{ + /** + * The registered transformers. + * + * @var list + */ + private array $items = []; + + /** + * Register built in Transformers. + */ + private function __construct() + { + $this->registerBuiltInTransformers(); + + usort($this->items, static fn (TransformerInterface $a, TransformerInterface $b): int => $b->getPriority() <=> $a->getPriority()); + } + + public static function createSingleton(): self + { + static $instance = null; + + if (!$instance) { + $instance = new self(); + } + + return $instance; + } + + /** + * Transform given Tokens collection through all Transformer classes. + * + * @param Tokens $tokens Tokens collection + */ + public function transform(Tokens $tokens): void + { + foreach ($this->items as $transformer) { + foreach ($tokens as $index => $token) { + $transformer->process($tokens, $token, $index); + } + } + } + + /** + * @param TransformerInterface $transformer Transformer + */ + private function registerTransformer(TransformerInterface $transformer): void + { + if (\PHP_VERSION_ID >= $transformer->getRequiredPhpVersionId()) { + $this->items[] = $transformer; + } + } + + private function registerBuiltInTransformers(): void + { + static $registered = false; + + if ($registered) { + return; + } + + $registered = true; + + foreach ($this->findBuiltInTransformers() as $transformer) { + $this->registerTransformer($transformer); + } + } + + /** + * @return iterable + */ + private function findBuiltInTransformers(): iterable + { + foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) { + $relativeNamespace = $file->getRelativePath(); + $class = __NAMESPACE__.'\Transformer\\'.('' !== $relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); + + $instance = new $class(); + + \assert($instance instanceof TransformerInterface); + + yield $instance; + } + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php new file mode 100644 index 0000000..cae4258 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Console\Application; + +/** + * Obtain information about using version of tool. + * + * @author Dariusz Rumiński + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class ToolInfo implements ToolInfoInterface +{ + public const COMPOSER_PACKAGE_NAME = 'friendsofphp/php-cs-fixer'; + + public const COMPOSER_LEGACY_PACKAGE_NAME = 'fabpot/php-cs-fixer'; + + /** + * @var null|array{name: string, version: string, dist: array{reference?: string}} + */ + private ?array $composerInstallationDetails = null; + + private ?bool $isInstalledByComposer = null; + + public function getComposerInstallationDetails(): array + { + if (!$this->isInstalledByComposer()) { + throw new \LogicException('Cannot get composer version for tool not installed by composer.'); + } + + if (null === $this->composerInstallationDetails) { + $composerInstalled = json_decode(file_get_contents($this->getComposerInstalledFile()), true, 512, \JSON_THROW_ON_ERROR); + + /** @var list $packages */ + $packages = $composerInstalled['packages'] ?? $composerInstalled; + + foreach ($packages as $package) { + if (\in_array($package['name'], [self::COMPOSER_PACKAGE_NAME, self::COMPOSER_LEGACY_PACKAGE_NAME], true)) { + $this->composerInstallationDetails = $package; + + break; + } + } + } + + return $this->composerInstallationDetails; + } + + public function getComposerVersion(): string + { + $package = $this->getComposerInstallationDetails(); + + $versionSuffix = ''; + + if (isset($package['dist']['reference'])) { + $versionSuffix = '#'.$package['dist']['reference']; + } + + return $package['version'].$versionSuffix; + } + + public function getVersion(): string + { + if ($this->isInstalledByComposer()) { + return Application::VERSION.':'.$this->getComposerVersion(); + } + + return Application::VERSION; + } + + public function isInstalledAsPhar(): bool + { + return str_starts_with(__DIR__, 'phar://'); + } + + public function isInstalledByComposer(): bool + { + if (null === $this->isInstalledByComposer) { + $this->isInstalledByComposer = !$this->isInstalledAsPhar() && file_exists($this->getComposerInstalledFile()); + } + + return $this->isInstalledByComposer; + } + + /** + * Determines if the tool is run inside our pre-built Docker image. + * The `/fixer/` path comes from our Dockerfile, tool is installed there and added to global PATH via symlinked binary. + */ + public function isRunInsideDocker(): bool + { + return str_starts_with(__FILE__, '/fixer/') && is_file('/.dockerenv'); + } + + public function getPharDownloadUri(string $version): string + { + return \sprintf( + 'https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', + $version, + ); + } + + private function getComposerInstalledFile(): string + { + return __DIR__.'/../../../composer/installed.json'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php new file mode 100644 index 0000000..9907f70 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface ToolInfoInterface +{ + /** + * @return array{name: string, version: string, dist: array{reference?: string}} + */ + public function getComposerInstallationDetails(): array; + + public function getComposerVersion(): string; + + public function getVersion(): string; + + public function isInstalledAsPhar(): bool; + + public function isInstalledByComposer(): bool; + + public function isRunInsideDocker(): bool; + + public function getPharDownloadUri(string $version): string; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/UnsupportedPhpVersionAllowedConfigInterface.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/UnsupportedPhpVersionAllowedConfigInterface.php new file mode 100644 index 0000000..9e02354 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/UnsupportedPhpVersionAllowedConfigInterface.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @TODO 4.0 Include in main ConfigInterface + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +interface UnsupportedPhpVersionAllowedConfigInterface extends ConfigInterface +{ + /** + * Returns true if execution should be allowed on unsupported PHP version whose syntax is not yet supported by the fixer. + */ + public function getUnsupportedPhpVersionAllowed(): bool; + + /** + * @return $this + */ + public function setUnsupportedPhpVersionAllowed(bool $isUnsupportedPhpVersionAllowed): ConfigInterface; +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Utils.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Utils.php new file mode 100644 index 0000000..58bdf61 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/Utils.php @@ -0,0 +1,224 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Tokenizer\Token; + +/** + * @author Dariusz Rumiński + * @author Graham Campbell + * @author Odín del Río + * + * @internal + * + * @deprecated This is a God Class anti-pattern. Don't expand it. It is fine to use logic that is already here (that's why we don't trigger deprecation warnings), but over time logic should be moved to dedicated, single-responsibility classes. + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class Utils +{ + private function __construct() + { + // cannot create instance + } + + /** + * Converts a camel cased string to a snake cased string. + */ + public static function camelCaseToUnderscore(string $string): string + { + return mb_strtolower( + Preg::replace( + '/(?isWhitespace()) { + throw new \InvalidArgumentException(\sprintf('The given token must be whitespace, got "%s".', $token->getName())); + } + + $str = strrchr( + str_replace(["\r\n", "\r"], "\n", $token->getContent()), + "\n", + ); + + if (false === $str) { + return ''; + } + + return ltrim($str, "\n"); + } + + /** + * Perform stable sorting using provided comparison function. + * + * Stability is ensured by using Schwartzian transform. + * + * @template T + * @template L of list + * @template R + * + * @param L $elements + * @param callable(T): R $getComparedValue a callable that takes a single element and returns the value to compare + * @param callable(R, R): int $compareValues a callable that compares two values + * + * @return L + */ + public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues): array + { + $sortItems = []; + foreach ($elements as $index => $element) { + $sortItems[] = [$element, $index, $getComparedValue($element)]; + } + + usort($sortItems, static function ($a, $b) use ($compareValues): int { + $comparison = $compareValues($a[2], $b[2]); + + if (0 !== $comparison) { + return $comparison; + } + + return $a[1] <=> $b[1]; + }); + + return array_map(static fn (array $item) => $item[0], $sortItems); // @phpstan-ignore return.type (PHPStan cannot understand that the result will still be L template) + } + + /** + * Sort fixers by their priorities, and by their names if priorities are equal. That is ensuring always deterministic order of fixers. + * + * @template T of list + * + * @param T $fixers + * + * @return T + */ + public static function sortFixers(array $fixers): array + { + usort($fixers, static function (FixerInterface $a, FixerInterface $b): int { + $cmpByPriority = $b->getPriority() <=> $a->getPriority(); + + return 0 !== $cmpByPriority + ? $cmpByPriority + : $a->getName() <=> $b->getName(); + }); + + return $fixers; // @phpstan-ignore return.type (PHPStan cannot understand that the result will still be T template) + } + + /** + * Join names in natural language using specified wrapper (double quote by default). + * + * @param list $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoin(array $names, string $wrapper = '"', string $lastJoin = 'and'): string + { + if (0 === \count($names)) { + throw new \InvalidArgumentException('Array of names cannot be empty.'); + } + + if (\strlen($wrapper) > 1) { + throw new \InvalidArgumentException('Wrapper should be a single-char string or empty.'); + } + + $names = array_map(static fn (string $name): string => \sprintf('%2$s%1$s%2$s', $name, $wrapper), $names); + + $last = array_pop($names); + + if (\count($names) > 0) { + return implode(', ', $names).' '.$lastJoin.' '.$last; + } + + return $last; + } + + /** + * Join names in natural language wrapped in backticks, e.g. `a`, `b` and `c`. + * + * @param list $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoinWithBackticks(array $names, string $lastJoin = 'and'): string + { + return self::naturalLanguageJoin($names, '`', $lastJoin); + } + + public static function convertArrayTypeToList(string $type): string + { + $parts = explode('[]', $type); + $count = \count($parts) - 1; + + return str_repeat('list<', $count).$parts[0].str_repeat('>', $count); + } + + /** + * @param mixed $value + */ + public static function toString($value): string + { + return \is_array($value) + ? self::arrayToString($value) + : self::scalarToString($value); + } + + /** + * @param mixed $value + */ + private static function scalarToString($value): string + { + $str = var_export($value, true); + + return Preg::replace('/\bNULL\b/', 'null', $str); + } + + /** + * @param array $value + */ + private static function arrayToString(array $value): string + { + if (0 === \count($value)) { + return '[]'; + } + + $isHash = !array_is_list($value); + $str = '['; + + foreach ($value as $k => $v) { + if ($isHash) { + $str .= self::scalarToString($k).' => '; + } + + $str .= \is_array($v) + ? self::arrayToString($v).', ' + : self::scalarToString($v).', '; + } + + return substr($str, 0, -2).']'; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php new file mode 100644 index 0000000..8dd11b2 --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WhitespacesFixerConfig +{ + /** @var non-empty-string */ + private string $indent; + + /** @var non-empty-string */ + private string $lineEnding; + + /** + * @param non-empty-string $indent + * @param non-empty-string $lineEnding + */ + public function __construct(string $indent = ' ', string $lineEnding = "\n") + { + if (!\in_array($indent, [' ', ' ', "\t"], true)) { + throw new \InvalidArgumentException('Invalid "indent" param, expected tab or two or four spaces.'); + } + + if (!\in_array($lineEnding, ["\n", "\r\n"], true)) { + throw new \InvalidArgumentException('Invalid "lineEnding" param, expected "\n" or "\r\n".'); + } + + $this->indent = $indent; + $this->lineEnding = $lineEnding; + } + + /** + * @return non-empty-string + */ + public function getIndent(): string + { + return $this->indent; + } + + /** + * @return non-empty-string + */ + public function getLineEnding(): string + { + return $this->lineEnding; + } +} diff --git a/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php new file mode 100644 index 0000000..0d44d5e --- /dev/null +++ b/trilhas_poo/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @readonly + * + * @internal + * + * @no-named-arguments Parameter names are not covered by the backward compatibility promise. + */ +final class WordMatcher +{ + /** + * @var list + */ + private array $candidates; + + /** + * @param list $candidates + */ + public function __construct(array $candidates) + { + $this->candidates = $candidates; + } + + public function match(string $needle): ?string + { + $word = null; + $distance = ceil(\strlen($needle) * 0.35); + + foreach ($this->candidates as $candidate) { + $candidateDistance = levenshtein($needle, $candidate); + + if ($candidateDistance < $distance) { + $word = $candidate; + $distance = $candidateDistance; + } + } + + return $word; + } +} diff --git a/trilhas_poo/vendor/psr/container/.gitignore b/trilhas_poo/vendor/psr/container/.gitignore new file mode 100644 index 0000000..b2395aa --- /dev/null +++ b/trilhas_poo/vendor/psr/container/.gitignore @@ -0,0 +1,3 @@ +composer.lock +composer.phar +/vendor/ diff --git a/trilhas_poo/vendor/psr/container/LICENSE b/trilhas_poo/vendor/psr/container/LICENSE new file mode 100644 index 0000000..2877a48 --- /dev/null +++ b/trilhas_poo/vendor/psr/container/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2016 container-interop +Copyright (c) 2016 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/trilhas_poo/vendor/psr/container/README.md b/trilhas_poo/vendor/psr/container/README.md new file mode 100644 index 0000000..1b9d9e5 --- /dev/null +++ b/trilhas_poo/vendor/psr/container/README.md @@ -0,0 +1,13 @@ +Container interface +============== + +This repository holds all interfaces related to [PSR-11 (Container Interface)][psr-url]. + +Note that this is not a Container implementation of its own. It is merely abstractions that describe the components of a Dependency Injection Container. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-11/ +[package-url]: https://packagist.org/packages/psr/container +[implementation-url]: https://packagist.org/providers/psr/container-implementation + diff --git a/trilhas_poo/vendor/psr/container/composer.json b/trilhas_poo/vendor/psr/container/composer.json new file mode 100644 index 0000000..baf6cd1 --- /dev/null +++ b/trilhas_poo/vendor/psr/container/composer.json @@ -0,0 +1,27 @@ +{ + "name": "psr/container", + "type": "library", + "description": "Common Container Interface (PHP FIG PSR-11)", + "keywords": ["psr", "psr-11", "container", "container-interop", "container-interface"], + "homepage": "https://github.com/php-fig/container", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=7.4.0" + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} diff --git a/trilhas_poo/vendor/psr/container/src/ContainerExceptionInterface.php b/trilhas_poo/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 0000000..0f213f2 --- /dev/null +++ b/trilhas_poo/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,12 @@ +=7.2.0" + }, + "autoload": { + "psr-4": { + "Psr\\EventDispatcher\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/trilhas_poo/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php b/trilhas_poo/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php new file mode 100644 index 0000000..4306fa9 --- /dev/null +++ b/trilhas_poo/vendor/psr/event-dispatcher/src/EventDispatcherInterface.php @@ -0,0 +1,21 @@ +logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/trilhas_poo/vendor/psr/log/composer.json b/trilhas_poo/vendor/psr/log/composer.json new file mode 100644 index 0000000..879fc6f --- /dev/null +++ b/trilhas_poo/vendor/psr/log/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/log", + "description": "Common interface for logging libraries", + "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} diff --git a/trilhas_poo/vendor/psr/log/src/AbstractLogger.php b/trilhas_poo/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 0000000..d60a091 --- /dev/null +++ b/trilhas_poo/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +logger = $logger; + } +} diff --git a/trilhas_poo/vendor/psr/log/src/LoggerInterface.php b/trilhas_poo/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 0000000..cb4cf64 --- /dev/null +++ b/trilhas_poo/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,98 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/trilhas_poo/vendor/psr/log/src/NullLogger.php b/trilhas_poo/vendor/psr/log/src/NullLogger.php new file mode 100644 index 0000000..de0561e --- /dev/null +++ b/trilhas_poo/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,26 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed[] $context + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + // noop + } +} diff --git a/trilhas_poo/vendor/react/cache/CHANGELOG.md b/trilhas_poo/vendor/react/cache/CHANGELOG.md new file mode 100644 index 0000000..ab59f18 --- /dev/null +++ b/trilhas_poo/vendor/react/cache/CHANGELOG.md @@ -0,0 +1,96 @@ +# Changelog + +## 1.2.0 (2022-11-30) + +* Feature: Support PHP 8.1 and PHP 8.2. + (#47 by @SimonFrings and #52 by @WyriHaximus) + +* Minor documentation improvements. + (#48 by @SimonFrings and #51 by @nhedger) + +* Update test suite and use GitHub actions for continuous integration (CI). + (#45 and #49 by @SimonFrings and #54 by @clue) + +## 1.1.0 (2020-09-18) + +* Feature: Forward compatibility with react/promise 3. + (#39 by @WyriHaximus) + +* Add `.gitattributes` to exclude dev files from exports. + (#40 by @reedy) + +* Improve test suite, update to support PHP 8 and PHPUnit 9.3. + (#41 and #43 by @SimonFrings and #42 by @WyriHaximus) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.6.0 release. + +## 0.6.0 (2019-07-04) + +* Feature / BC break: Add support for `getMultiple()`, `setMultiple()`, `deleteMultiple()`, `clear()` and `has()` + supporting multiple cache items (inspired by PSR-16). + (#32 by @krlv and #37 by @clue) + +* Documentation for TTL precision with millisecond accuracy or below and + use high-resolution timer for cache TTL on PHP 7.3+. + (#35 and #38 by @clue) + +* Improve API documentation and allow legacy HHVM to fail in Travis CI config. + (#34 and #36 by @clue) + +* Prefix all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#31 by @WyriHaximus) + +## 0.5.0 (2018-06-25) + +* Improve documentation by describing what is expected of a class implementing `CacheInterface`. + (#21, #22, #23, #27 by @WyriHaximus) + +* Implemented (optional) Least Recently Used (LRU) cache algorithm for `ArrayCache`. + (#26 by @clue) + +* Added support for cache expiration (TTL). + (#29 by @clue and @WyriHaximus) + +* Renamed `remove` to `delete` making it more in line with `PSR-16`. + (#30 by @clue) + +## 0.4.2 (2017-12-20) + +* Improve documentation with usage and installation instructions + (#10 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` and + add forward compatibility with PHPUnit 5 and PHPUnit 6 and + sanitize Composer autoload paths + (#14 by @shaunbramley and #12 and #18 by @clue) + +## 0.4.1 (2016-02-25) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#9 by @clue) +* Adjust compatibility to 5.3 (#7 by @clue) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.0 (2013-04-14) + +* Version bump + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS diff --git a/trilhas_poo/vendor/react/cache/LICENSE b/trilhas_poo/vendor/react/cache/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/cache/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/cache/README.md b/trilhas_poo/vendor/react/cache/README.md new file mode 100644 index 0000000..7a86be9 --- /dev/null +++ b/trilhas_poo/vendor/react/cache/README.md @@ -0,0 +1,367 @@ +# Cache + +[![CI status](https://github.com/reactphp/cache/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/cache/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/cache?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/cache) + +Async, [Promise](https://github.com/reactphp/promise)-based cache interface +for [ReactPHP](https://reactphp.org/). + +The cache component provides a +[Promise](https://github.com/reactphp/promise)-based +[`CacheInterface`](#cacheinterface) and an in-memory [`ArrayCache`](#arraycache) +implementation of that. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. +This project is heavily inspired by +[PSR-16: Common Interface for Caching Libraries](https://www.php-fig.org/psr/psr-16/), +but uses an interface more suited for async, non-blocking applications. + +**Table of Contents** + +* [Usage](#usage) + * [CacheInterface](#cacheinterface) + * [get()](#get) + * [set()](#set) + * [delete()](#delete) + * [getMultiple()](#getmultiple) + * [setMultiple()](#setmultiple) + * [deleteMultiple()](#deletemultiple) + * [clear()](#clear) + * [has()](#has) + * [ArrayCache](#arraycache) +* [Common usage](#common-usage) + * [Fallback get](#fallback-get) + * [Fallback-get-and-set](#fallback-get-and-set) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +### CacheInterface + +The `CacheInterface` describes the main interface of this component. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. + +#### get() + +The `get(string $key, mixed $default = null): PromiseInterface` method can be used to +retrieve an item from the cache. + +This method will resolve with the cached value on success or with the +given `$default` value when no item can be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache + ->get('foo') + ->then('var_dump'); +``` + +This example fetches the value of the key `foo` and passes it to the +`var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +#### set() + +The `set(string $key, mixed $value, ?float $ttl = null): PromiseInterface` method can be used to +store an item in the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for this cache item. If this parameter is omitted (or `null`), the item +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache item results in a cache miss, +see also [`get()`](#get). + +```php +$cache->set('foo', 'bar', 60); +``` + +This example eventually sets the value of the key `foo` to `bar`. If it +already exists, it is overridden. + +This interface does not enforce any particular TTL resolution, so special +care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Cache implementations SHOULD work on a +best effort basis and SHOULD provide at least second accuracy unless +otherwise noted. Many existing cache implementations are known to provide +microsecond or millisecond accuracy, but it's generally not recommended +to rely on this high precision. + +This interface suggests that cache implementations SHOULD use a monotonic +time source if available. Given that a monotonic time source is only +available as of PHP 7.3 by default, cache implementations MAY fall back +to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s and then +adjust your system time forward by 20s, the cache item SHOULD still +expire in 30s. + +#### delete() + +The `delete(string $key): PromiseInterface` method can be used to +delete an item from the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. When no item for `$key` is found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->delete('foo'); +``` + +This example eventually deletes the key `foo` from the cache. As with +`set()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### getMultiple() + +The `getMultiple(string[] $keys, mixed $default = null): PromiseInterface` method can be used to +retrieve multiple cache items by their unique keys. + +This method will resolve with an array of cached values on success or with the +given `$default` value when an item can not be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache->getMultiple(array('name', 'age'))->then(function (array $values) { + $name = $values['name'] ?? 'User'; + $age = $values['age'] ?? 'n/a'; + + echo $name . ' is ' . $age . PHP_EOL; +}); +``` + +This example fetches the cache items for the `name` and `age` keys and +prints some example output. You can use any of the composition provided +by [promises](https://github.com/reactphp/promise). + +#### setMultiple() + +The `setMultiple(array $values, ?float $ttl = null): PromiseInterface` method can be used to +persist a set of key => value pairs in the cache, with an optional TTL. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for these cache items. If this parameter is omitted (or `null`), these items +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache items results in a cache miss, +see also [`getMultiple()`](#getmultiple). + +```php +$cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); +``` + +This example eventually sets the list of values - the key `foo` to `1` value +and the key `bar` to `2`. If some of the keys already exist, they are overridden. + +#### deleteMultiple() + +The `setMultiple(string[] $keys): PromiseInterface` method can be used to +delete multiple cache items in a single operation. + +This method will resolve with `true` on success or `false` when an error +occurs. When no items for `$keys` are found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->deleteMultiple(array('foo', 'bar, 'baz')); +``` + +This example eventually deletes keys `foo`, `bar` and `baz` from the cache. +As with `setMultiple()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### clear() + +The `clear(): PromiseInterface` method can be used to +wipe clean the entire cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->clear(); +``` + +This example eventually deletes all keys from the cache. As with `deleteMultiple()`, +this may not happen instantly and a promise is returned to provide guarantees +whether or not all the items have been removed from cache. + +#### has() + +The `has(string $key): PromiseInterface` method can be used to +determine whether an item is present in the cache. + +This method will resolve with `true` on success or `false` when no item can be found +or when an error occurs. Similarly, an expired cache item (once the time-to-live +is expired) is considered a cache miss. + +```php +$cache + ->has('foo') + ->then('var_dump'); +``` + +This example checks if the value of the key `foo` is set in the cache and passes +the result to the `var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +NOTE: It is recommended that has() is only to be used for cache warming type purposes +and not to be used within your live applications operations for get/set, as this method +is subject to a race condition where your has() will return true and immediately after, +another script can remove it making the state of your app out of date. + +### ArrayCache + +The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface). + +```php +$cache = new ArrayCache(); + +$cache->set('foo', 'bar'); +``` + +Its constructor accepts an optional `?int $limit` parameter to limit the +maximum number of entries to store in the LRU cache. If you add more +entries to this instance, it will automatically take care of removing +the one that was least recently used (LRU). + +For example, this snippet will overwrite the first value and only store +the last two entries: + +```php +$cache = new ArrayCache(2); + +$cache->set('foo', '1'); +$cache->set('bar', '2'); +$cache->set('baz', '3'); +``` + +This cache implementation is known to rely on wall-clock time to schedule +future cache expiration times when using any version before PHP 7.3, +because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s on PHP < 7.3 +and then adjust your system time forward by 20s, the cache item may +expire in 10s. See also [`set()`](#set) for more details. + +## Common usage + +### Fallback get + +A common use case of caches is to attempt fetching a cached value and as a +fallback retrieve it from the original data source if not found. Here is an +example of that: + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return getFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); +``` + +First an attempt is made to retrieve the value of `foo`. A callback function is +registered that will call `getFooFromDb` when the resulting value is null. +`getFooFromDb` is a function (can be any PHP callable) that will be called if the +key does not exist in the cache. + +`getFooFromDb` can handle the missing key by returning a promise for the +actual value from the database (or any other data source). As a result, this +chain will correctly fall back, and provide the value in both cases. + +### Fallback get and set + +To expand on the fallback get example, often you want to set the value on the +cache after fetching it from the data source. + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return $this->getAndCacheFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); + +public function getAndCacheFooFromDb() +{ + return $this->db + ->get('foo') + ->then(array($this, 'cacheFooFromDb')); +} + +public function cacheFooFromDb($foo) +{ + $this->cache->set('foo', $foo); + + return $foo; +} +``` + +By using chaining you can easily conditionally cache the value if it is +fetched from the database. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/cache:^1.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/trilhas_poo/vendor/react/cache/composer.json b/trilhas_poo/vendor/react/cache/composer.json new file mode 100644 index 0000000..153439a --- /dev/null +++ b/trilhas_poo/vendor/react/cache/composer.json @@ -0,0 +1,45 @@ +{ + "name": "react/cache", + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": ["cache", "caching", "promise", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Cache\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/cache/src/ArrayCache.php b/trilhas_poo/vendor/react/cache/src/ArrayCache.php new file mode 100644 index 0000000..81f25ef --- /dev/null +++ b/trilhas_poo/vendor/react/cache/src/ArrayCache.php @@ -0,0 +1,181 @@ +set('foo', 'bar'); + * ``` + * + * Its constructor accepts an optional `?int $limit` parameter to limit the + * maximum number of entries to store in the LRU cache. If you add more + * entries to this instance, it will automatically take care of removing + * the one that was least recently used (LRU). + * + * For example, this snippet will overwrite the first value and only store + * the last two entries: + * + * ```php + * $cache = new ArrayCache(2); + * + * $cache->set('foo', '1'); + * $cache->set('bar', '2'); + * $cache->set('baz', '3'); + * ``` + * + * This cache implementation is known to rely on wall-clock time to schedule + * future cache expiration times when using any version before PHP 7.3, + * because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s on PHP < 7.3 + * and then adjust your system time forward by 20s, the cache item may + * expire in 10s. See also [`set()`](#set) for more details. + * + * @param int|null $limit maximum number of entries to store in the LRU cache + */ + public function __construct($limit = null) + { + $this->limit = $limit; + + // prefer high-resolution timer, available as of PHP 7.3+ + $this->supportsHighResolution = \function_exists('hrtime'); + } + + public function get($key, $default = null) + { + // delete key if it is already expired => below will detect this as a cache miss + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve($default); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return Promise\resolve($value); + } + + public function set($key, $value, $ttl = null) + { + // unset before setting to ensure this entry will be added to end of array (LRU info) + unset($this->data[$key]); + $this->data[$key] = $value; + + // sort expiration times if TTL is given (first will expire first) + unset($this->expires[$key]); + if ($ttl !== null) { + $this->expires[$key] = $this->now() + $ttl; + \asort($this->expires); + } + + // ensure size limit is not exceeded or remove first entry from array + if ($this->limit !== null && \count($this->data) > $this->limit) { + // first try to check if there's any expired entry + // expiration times are sorted, so we can simply look at the first one + \reset($this->expires); + $key = \key($this->expires); + + // check to see if the first in the list of expiring keys is already expired + // if the first key is not expired, we have to overwrite by using LRU info + if ($key === null || $this->now() - $this->expires[$key] < 0) { + \reset($this->data); + $key = \key($this->data); + } + unset($this->data[$key], $this->expires[$key]); + } + + return Promise\resolve(true); + } + + public function delete($key) + { + unset($this->data[$key], $this->expires[$key]); + + return Promise\resolve(true); + } + + public function getMultiple(array $keys, $default = null) + { + $values = array(); + + foreach ($keys as $key) { + $values[$key] = $this->get($key, $default); + } + + return Promise\all($values); + } + + public function setMultiple(array $values, $ttl = null) + { + foreach ($values as $key => $value) { + $this->set($key, $value, $ttl); + } + + return Promise\resolve(true); + } + + public function deleteMultiple(array $keys) + { + foreach ($keys as $key) { + unset($this->data[$key], $this->expires[$key]); + } + + return Promise\resolve(true); + } + + public function clear() + { + $this->data = array(); + $this->expires = array(); + + return Promise\resolve(true); + } + + public function has($key) + { + // delete key if it is already expired + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve(false); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return Promise\resolve(true); + } + + /** + * @return float + */ + private function now() + { + return $this->supportsHighResolution ? \hrtime(true) * 1e-9 : \microtime(true); + } +} diff --git a/trilhas_poo/vendor/react/cache/src/CacheInterface.php b/trilhas_poo/vendor/react/cache/src/CacheInterface.php new file mode 100644 index 0000000..8e51c19 --- /dev/null +++ b/trilhas_poo/vendor/react/cache/src/CacheInterface.php @@ -0,0 +1,194 @@ +get('foo') + * ->then('var_dump'); + * ``` + * + * This example fetches the value of the key `foo` and passes it to the + * `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * @param string $key + * @param mixed $default Default value to return for cache miss or null if not given. + * @return PromiseInterface + */ + public function get($key, $default = null); + + /** + * Stores an item in the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for this cache item. If this parameter is omitted (or `null`), the item + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache item results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->set('foo', 'bar', 60); + * ``` + * + * This example eventually sets the value of the key `foo` to `bar`. If it + * already exists, it is overridden. + * + * This interface does not enforce any particular TTL resolution, so special + * care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Cache implementations SHOULD work on a + * best effort basis and SHOULD provide at least second accuracy unless + * otherwise noted. Many existing cache implementations are known to provide + * microsecond or millisecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * This interface suggests that cache implementations SHOULD use a monotonic + * time source if available. Given that a monotonic time source is only + * available as of PHP 7.3 by default, cache implementations MAY fall back + * to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s and then + * adjust your system time forward by 20s, the cache item SHOULD still + * expire in 30s. + * + * @param string $key + * @param mixed $value + * @param ?float $ttl + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function set($key, $value, $ttl = null); + + /** + * Deletes an item from the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. When no item for `$key` is found in the cache, it also resolves + * to `true`. If the cache implementation has to go over the network to + * delete it, it may take a while. + * + * ```php + * $cache->delete('foo'); + * ``` + * + * This example eventually deletes the key `foo` from the cache. As with + * `set()`, this may not happen instantly and a promise is returned to + * provide guarantees whether or not the item has been removed from cache. + * + * @param string $key + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function delete($key); + + /** + * Retrieves multiple cache items by their unique keys. + * + * This method will resolve with an array of cached values on success or with the + * given `$default` value when an item can not be found or when an error occurs. + * Similarly, an expired cache item (once the time-to-live is expired) is + * considered a cache miss. + * + * ```php + * $cache->getMultiple(array('name', 'age'))->then(function (array $values) { + * $name = $values['name'] ?? 'User'; + * $age = $values['age'] ?? 'n/a'; + * + * echo $name . ' is ' . $age . PHP_EOL; + * }); + * ``` + * + * This example fetches the cache items for the `name` and `age` keys and + * prints some example output. You can use any of the composition provided + * by [promises](https://github.com/reactphp/promise). + * + * @param string[] $keys A list of keys that can obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * @return PromiseInterface Returns a promise which resolves to an `array` of cached values + */ + public function getMultiple(array $keys, $default = null); + + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for these cache items. If this parameter is omitted (or `null`), these items + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache items results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); + * ``` + * + * This example eventually sets the list of values - the key `foo` to 1 value + * and the key `bar` to 2. If some of the keys already exist, they are overridden. + * + * @param array $values A list of key => value pairs for a multiple-set operation. + * @param ?float $ttl Optional. The TTL value of this item. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function setMultiple(array $values, $ttl = null); + + /** + * Deletes multiple cache items in a single operation. + * + * @param string[] $keys A list of string-based keys to be deleted. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function deleteMultiple(array $keys); + + /** + * Wipes clean the entire cache. + * + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function clear(); + + /** + * Determines whether an item is present in the cache. + * + * This method will resolve with `true` on success or `false` when no item can be found + * or when an error occurs. Similarly, an expired cache item (once the time-to-live + * is expired) is considered a cache miss. + * + * ```php + * $cache + * ->has('foo') + * ->then('var_dump'); + * ``` + * + * This example checks if the value of the key `foo` is set in the cache and passes + * the result to the `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * NOTE: It is recommended that has() is only to be used for cache warming type purposes + * and not to be used within your live applications operations for get/set, as this method + * is subject to a race condition where your has() will return true and immediately after, + * another script can remove it making the state of your app out of date. + * + * @param string $key The cache item key. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function has($key); +} diff --git a/trilhas_poo/vendor/react/child-process/CHANGELOG.md b/trilhas_poo/vendor/react/child-process/CHANGELOG.md new file mode 100644 index 0000000..3ee0221 --- /dev/null +++ b/trilhas_poo/vendor/react/child-process/CHANGELOG.md @@ -0,0 +1,186 @@ +# Changelog + +## 0.6.7 (2025-12-23) + +Just in time for the holidays, we are happy to announce the release of `v0.6.7`! 🎄🎉 + +This is a compatibility release that contains backported features from the `0.7.x` branch. +Once v0.7 is released, it will be the way forward for this project. + +* Feature: Improve PHP 8.5+ support by replacing binary cast with string cast. + (#119 by @kubawerlos and @WyriHaximus) + +## 0.6.6 (2025-01-01) + +This is a compatibility release that contains backported features from the `0.7.x` branch. +Once v0.7 is released, it will be the way forward for this project. + +* Feature: Improve PHP 8.4+ support by avoiding implicitly nullable types. + (#114 by @clue) + +* Improve test suite to run tests on latest PHP versions and report failed assertions. + (#113 by @clue) + +## 0.6.5 (2022-09-16) + +* Feature: Full support for PHP 8.1 and PHP 8.2 release. + (#91 by @SimonFrings and #99 by @WyriHaximus) + +* Feature / Fix: Improve error reporting when custom error handler is used. + (#94 by @clue) + +* Minor documentation improvements. + (#92 by @SimonFrings and #95 by @nhedger) + +* Improve test suite, skip failing tests on bugged versions and fix legacy HHVM build. + (#96 and #98 by @clue and #93 by @SimonFrings) + +## 0.6.4 (2021-10-12) + +* Feature / Fix: Skip sigchild check if `phpinfo()` has been disabled. + (#89 by @clue) + +* Fix: Fix detecting closed socket pipes on PHP 8. + (#90 by @clue) + +## 0.6.3 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#87 by @clue) + + ```php + // old (still supported) + $process = new React\ChildProcess\Process($command); + $process->start($loop); + + // new (using default loop) + $process = new React\ChildProcess\Process($command); + $process->start(); + ``` + +## 0.6.2 (2021-02-05) + +* Feature: Support PHP 8 and add non-blocking I/O support on Windows with PHP 8. + (#85 by @clue) + +* Minor documentation improvements. + (#78 by @WyriHaximus and #80 by @gdejong) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9, switch to GitHub actions and clean up test suite. + (#75 by @reedy, #81 by @gdejong, #82 by @SimonFrings and #84 by @clue) + +## 0.6.1 (2019-02-15) + +* Feature / Fix: Improve error reporting when spawning child process fails. + (#73 by @clue) + +## 0.6.0 (2019-01-14) + +A major feature release with some minor API improvements! +This project now has limited Windows support and supports passing custom pipes +and file descriptors to the child process. + +This update involves a few minor BC breaks. We've tried hard to avoid BC breaks +where possible and minimize impact otherwise. We expect that most consumers of +this package will actually not be affected by any BC breaks, see below for more +details. + +* Feature / BC break: Support passing custom pipes and file descriptors to child process, + expose all standard I/O pipes in an array and remove unused Windows-only options. + (#62, #64 and #65 by @clue) + + > BC note: The optional `$options` parameter in the `Process` constructor + has been removed and a new `$fds` parameter has been added instead. The + previous `$options` parameter was Windows-only, available options were not + documented or referenced anywhere else in this library, so its actual + impact is expected to be relatively small. See the documentation and the + following changelog entry if you're looking for Windows support. + +* Feature: Support spawning child process on Windows without process I/O pipes. + (#67 by @clue) + +* Feature / BC break: Improve sigchild compatibility and support explicit configuration. + (#63 by @clue) + + ```php + // advanced: not recommended by default + Process::setSigchildEnabled(true); + ``` + + > BC note: The old public sigchild methods have been removed, but its + practical impact is believed to be relatively small due to the automatic detection. + +* Improve performance by prefixing all global functions calls with \ to skip + the look up and resolve process and go straight to the global function. + (#68 by @WyriHaximus) + +* Minor documentation improvements and docblock updates. + (#59 by @iamluc and #69 by @CharlotteDunois) + +* Improve test suite to test against PHP7.2 and PHP 7.3, improve HHVM compatibility, + add forward compatibility with PHPUnit 7 and run tests on Windows via Travis CI. + (#66 and #71 by @clue) + +## 0.5.2 (2018-01-18) + +* Feature: Detect "exit" immediately if last process pipe is closed + (#58 by @clue) + + This introduces a simple check to see if the program is already known to be + closed when the last process pipe is closed instead of relying on a periodic + timer. This simple change improves "exit" detection significantly for most + programs and does not cause a noticeable penalty for more advanced use cases. + +* Fix forward compatibility with upcoming EventLoop releases + (#56 by @clue) + +## 0.5.1 (2017-12-22) + +* Fix: Update Stream dependency to work around SEGFAULT in legacy PHP < 5.4.28 + and PHP < 5.5.12 + (#50 and #52 by @clue) + +* Improve test suite by simplifying test bootstrapping logic via Composer and + adding forward compatibility with PHPUnit 6 + (#53, #54 and #55 by @clue) + +## 0.5.0 (2017-08-15) + +* Forward compatibility: react/event-loop 1.0 and 0.5, react/stream 0.7.2 and 1.0, and Événement 3.0 + (#38 and #44 by @WyriHaximus, and #46 by @clue) +* Windows compatibility: Documentate that windows isn't supported in 0.5 unless used from within WSL + (#41 and #47 by @WyriHaximus) +* Documentation: Termination examples + (#42 by @clue) +* BC: Throw LogicException in Process instanciating when on Windows or when proc_open is missing (was `RuntimeException`) + (#49 by @mdrost) + +## 0.4.3 (2017-03-14) + +* Ease getting started by improving documentation and adding examples + (#33 and #34 by @clue) + +* First class support for PHP 5.3 through PHP 7.1 and HHVM + (#29 by @clue and #32 by @WyriHaximus) + +## 0.4.2 (2017-03-10) + +* Feature: Forward compatibility with Stream v0.5 + (#26 by @clue) + +* Improve test suite by removing AppVeyor and adding PHPUnit to `require-dev` + (#27 and #28 by @clue) + +## 0.4.1 (2016-08-01) + +* Standalone component +* Test against PHP 7 and HHVM, report test coverage, AppVeyor tests +* Wait for stdout and stderr to close before watching for process exit + (#18 by @mbonneau) + +## 0.4.0 (2014-02-02) + +* Feature: Added ChildProcess to run async child processes within the event loop (@jmikola) diff --git a/trilhas_poo/vendor/react/child-process/LICENSE b/trilhas_poo/vendor/react/child-process/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/child-process/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/child-process/README.md b/trilhas_poo/vendor/react/child-process/README.md new file mode 100644 index 0000000..34db320 --- /dev/null +++ b/trilhas_poo/vendor/react/child-process/README.md @@ -0,0 +1,619 @@ +# ChildProcess + +[![CI status](https://github.com/reactphp/child-process/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/child-process/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/child-process?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/child-process) + +Event-driven library for executing child processes with +[ReactPHP](https://reactphp.org/). + +This library integrates [Program Execution](http://php.net/manual/en/book.exec.php) +with the [EventLoop](https://github.com/reactphp/event-loop). +Child processes launched may be signaled and will emit an +`exit` event upon termination. +Additionally, process I/O streams (i.e. STDIN, STDOUT, STDERR) are exposed +as [Streams](https://github.com/reactphp/stream). + +**Table of contents** + +* [Quickstart example](#quickstart-example) +* [Process](#process) + * [Stream Properties](#stream-properties) + * [Command](#command) + * [Termination](#termination) + * [Custom pipes](#custom-pipes) + * [Sigchild Compatibility](#sigchild-compatibility) + * [Windows Compatibility](#windows-compatibility) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +```php +$process = new React\ChildProcess\Process('echo foo'); +$process->start(); + +$process->stdout->on('data', function ($chunk) { + echo $chunk; +}); + +$process->on('exit', function($exitCode, $termSignal) { + echo 'Process exited with code ' . $exitCode . PHP_EOL; +}); +``` + +See also the [examples](examples). + +## Process + +### Stream Properties + +Once a process is started, its I/O streams will be constructed as instances of +`React\Stream\ReadableStreamInterface` and `React\Stream\WritableStreamInterface`. +Before `start()` is called, these properties are not set. Once a process terminates, +the streams will become closed but not unset. + +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams as given below by default. +You can use the named references for common use cases or access these as an +array with all three pipes. + +* `$stdin` or `$pipes[0]` is a `WritableStreamInterface` +* `$stdout` or `$pipes[1]` is a `ReadableStreamInterface` +* `$stderr` or `$pipes[2]` is a `ReadableStreamInterface` + +Note that this default configuration may be overridden by explicitly passing +[custom pipes](#custom-pipes), in which case they may not be set or be assigned +different values. In particular, note that [Windows support](#windows-compatibility) +is limited in that it doesn't support non-blocking STDIO pipes. The `$pipes` +array will always contain references to all pipes as configured and the standard +I/O references will always be set to reference the pipes matching the above +conventions. See [custom pipes](#custom-pipes) for more details. + +Because each of these implement the underlying +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) or +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface), +you can use any of their events and methods as usual: + +```php +$process = new Process($command); +$process->start(); + +$process->stdout->on('data', function ($chunk) { + echo $chunk; +}); + +$process->stdout->on('end', function () { + echo 'ended'; +}); + +$process->stdout->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage(); +}); + +$process->stdout->on('close', function () { + echo 'closed'; +}); + +$process->stdin->write($data); +$process->stdin->end($data = null); +// … +``` + +For more details, see the +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) and +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface). + +### Command + +The `Process` class allows you to pass any kind of command line string: + +```php +$process = new Process('echo test'); +$process->start(); +``` + +The command line string usually consists of a whitespace-separated list with +your main executable bin and any number of arguments. Special care should be +taken to escape or quote any arguments, escpecially if you pass any user input +along. Likewise, keep in mind that especially on Windows, it is rather common to +have path names containing spaces and other special characters. If you want to +run a binary like this, you will have to ensure this is quoted as a single +argument using `escapeshellarg()` like this: + +```php +$bin = 'C:\\Program files (x86)\\PHP\\php.exe'; +$file = 'C:\\Users\\me\\Desktop\\Application\\main.php'; + +$process = new Process(escapeshellarg($bin) . ' ' . escapeshellarg($file)); +$process->start(); +``` + +By default, PHP will launch processes by wrapping the given command line string +in a `sh` command on Unix, so that the first example will actually execute +`sh -c echo test` under the hood on Unix. On Windows, it will not launch +processes by wrapping them in a shell. + +This is a very useful feature because it does not only allow you to pass single +commands, but actually allows you to pass any kind of shell command line and +launch multiple sub-commands using command chains (with `&&`, `||`, `;` and +others) and allows you to redirect STDIO streams (with `2>&1` and family). +This can be used to pass complete command lines and receive the resulting STDIO +streams from the wrapping shell command like this: + +```php +$process = new Process('echo run && demo || echo failed'); +$process->start(); +``` + +> Note that [Windows support](#windows-compatibility) is limited in that it + doesn't support STDIO streams at all and also that processes will not be run + in a wrapping shell by default. If you want to run a shell built-in function + such as `echo hello` or `sleep 10`, you may have to prefix your command line + with an explicit shell like `cmd /c echo hello`. + +In other words, the underlying shell is responsible for managing this command +line and launching the individual sub-commands and connecting their STDIO +streams as appropriate. +This implies that the `Process` class will only receive the resulting STDIO +streams from the wrapping shell, which will thus contain the complete +input/output with no way to discern the input/output of single sub-commands. + +If you want to discern the output of single sub-commands, you may want to +implement some higher-level protocol logic, such as printing an explicit +boundary between each sub-command like this: + +```php +$process = new Process('cat first && echo --- && cat second'); +$process->start(); +``` + +As an alternative, considering launching one process at a time and listening on +its `exit` event to conditionally start the next process in the chain. +This will give you an opportunity to configure the subsequent process I/O streams: + +```php +$first = new Process('cat first'); +$first->start(); + +$first->on('exit', function () { + $second = new Process('cat second'); + $second->start(); +}); +``` + +Keep in mind that PHP uses the shell wrapper for ALL command lines on Unix. +While this may seem reasonable for more complex command lines, this actually +also applies to running the most simple single command: + +```php +$process = new Process('yes'); +$process->start(); +``` + +This will actually spawn a command hierarchy similar to this on Unix: + +``` +5480 … \_ php example.php +5481 … \_ sh -c yes +5482 … \_ yes +``` + +This means that trying to get the underlying process PID or sending signals +will actually target the wrapping shell, which may not be the desired result +in many cases. + +If you do not want this wrapping shell process to show up, you can simply +prepend the command string with `exec` on Unix platforms, which will cause the +wrapping shell process to be replaced by our process: + +```php +$process = new Process('exec yes'); +$process->start(); +``` + +This will show a resulting command hierarchy similar to this: + +``` +5480 … \_ php example.php +5481 … \_ yes +``` + +This means that trying to get the underlying process PID and sending signals +will now target the actual command as expected. + +Note that in this case, the command line will not be run in a wrapping shell. +This implies that when using `exec`, there's no way to pass command lines such +as those containing command chains or redirected STDIO streams. + +As a rule of thumb, most commands will likely run just fine with the wrapping +shell. +If you pass a complete command line (or are unsure), you SHOULD most likely keep +the wrapping shell. +If you're running on Unix and you want to pass an invidual command only, you MAY +want to consider prepending the command string with `exec` to avoid the wrapping shell. + +### Termination + +The `exit` event will be emitted whenever the process is no longer running. +Event listeners will receive the exit code and termination signal as two +arguments: + +```php +$process = new Process('sleep 10'); +$process->start(); + +$process->on('exit', function ($code, $term) { + if ($term === null) { + echo 'exit with code ' . $code . PHP_EOL; + } else { + echo 'terminated with signal ' . $term . PHP_EOL; + } +}); +``` + +Note that `$code` is `null` if the process has terminated, but the exit +code could not be determined (for example +[sigchild compatibility](#sigchild-compatibility) was disabled). +Similarly, `$term` is `null` unless the process has terminated in response to +an uncaught signal sent to it. +This is not a limitation of this project, but actual how exit codes and signals +are exposed on POSIX systems, for more details see also +[here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). + +It's also worth noting that process termination depends on all file descriptors +being closed beforehand. +This means that all [process pipes](#stream-properties) will emit a `close` +event before the `exit` event and that no more `data` events will arrive after +the `exit` event. +Accordingly, if either of these pipes is in a paused state (`pause()` method +or internally due to a `pipe()` call), this detection may not trigger. + +The `terminate(?int $signal = null): bool` method can be used to send the +process a signal (SIGTERM by default). +Depending on which signal you send to the process and whether it has a signal +handler registered, this can be used to either merely signal a process or even +forcefully terminate it. + +```php +$process->terminate(SIGUSR1); +``` + +Keep the above section in mind if you want to forcefully terminate a process. +If your process spawn sub-processes or implicitly uses the +[wrapping shell mentioned above](#command), its file descriptors may be +inherited to child processes and terminating the main process may not +necessarily terminate the whole process tree. +It is highly suggested that you explicitly `close()` all process pipes +accordingly when terminating a process: + +```php +$process = new Process('sleep 10'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + foreach ($process->pipes as $pipe) { + $pipe->close(); + } + $process->terminate(); +}); +``` + +For many simple programs these seamingly complicated steps can also be avoided +by prefixing the command line with `exec` to avoid the wrapping shell and its +inherited process pipes as [mentioned above](#command). + +```php +$process = new Process('exec sleep 10'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + $process->terminate(); +}); +``` + +Many command line programs also wait for data on `STDIN` and terminate cleanly +when this pipe is closed. +For example, the following can be used to "soft-close" a `cat` process: + +```php +$process = new Process('cat'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + $process->stdin->end(); +}); +``` + +While process pipes and termination may seem confusing to newcomers, the above +properties actually allow some fine grained control over process termination, +such as first trying a soft-close and then applying a force-close after a +timeout. + +### Custom pipes + +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams by default. For more +advanced use cases it may be useful to pass in custom pipes, such as explicitly +passing additional file descriptors (FDs) or overriding default process pipes. + +Note that passing custom pipes is considered advanced usage and requires a +more in-depth understanding of Unix file descriptors and how they are inherited +to child processes and shared in multi-processing applications. + +If you do not want to use the default standard I/O pipes, you can explicitly +pass an array containing the file descriptor specification to the constructor +like this: + +```php +$fds = array( + // standard I/O pipes for stdin/stdout/stderr + 0 => array('pipe', 'r'), + 1 => array('pipe', 'w'), + 2 => array('pipe', 'w'), + + // example FDs for files or open resources + 4 => array('file', '/dev/null', 'r'), + 6 => fopen('log.txt','a'), + 8 => STDERR, + + // example FDs for sockets + 10 => fsockopen('localhost', 8080), + 12 => stream_socket_server('tcp://0.0.0.0:4711') +); + +$process = new Process($cmd, null, null, $fds); +$process->start(); +``` + +Unless your use case has special requirements that demand otherwise, you're +highly recommended to (at least) pass in the standard I/O pipes as given above. +The file descriptor specification accepts arguments in the exact same format +as the underlying [`proc_open()`](http://php.net/proc_open) function. + +Once the process is started, the `$pipes` array will always contain references to +all pipes as configured and the standard I/O references will always be set to +reference the pipes matching common Unix conventions. This library supports any +number of pipes and additional file descriptors, but many common applications +being run as a child process will expect that the parent process properly +assigns these file descriptors. + +### Sigchild Compatibility + +Internally, this project uses a work-around to improve compatibility when PHP +has been compiled with the `--enable-sigchild` option. This should not affect most +installations as this configure option is not used by default and many +distributions (such as Debian and Ubuntu) are known to not use this by default. +Some installations that use [Oracle OCI8](http://php.net/manual/en/book.oci8.php) +may use this configure option to circumvent `defunct` processes. + +When PHP has been compiled with the `--enable-sigchild` option, a child process' +exit code cannot be reliably determined via `proc_close()` or `proc_get_status()`. +To work around this, we execute the child process with an additional pipe and +use that to retrieve its exit code. + +This work-around incurs some overhead, so we only trigger this when necessary +and when we detect that PHP has been compiled with the `--enable-sigchild` option. +Because PHP does not provide a way to reliably detect this option, we try to +inspect output of PHP's configure options from the `phpinfo()` function. + +The static `setSigchildEnabled(bool $sigchild): void` method can be used to +explicitly enable or disable this behavior like this: + +```php +// advanced: not recommended by default +Process::setSigchildEnabled(true); +``` + +Note that all processes instantiated after this method call will be affected. +If this work-around is disabled on an affected PHP installation, the `exit` +event may receive `null` instead of the actual exit code as described above. +Similarly, some distributions are known to omit the configure options from +`phpinfo()`, so automatic detection may fail to enable this work-around in some +cases. You may then enable this explicitly as given above. + +**Note:** The original functionality was taken from Symfony's +[Process](https://github.com/symfony/process) compoment. + +### Windows Compatibility + +Due to platform constraints, this library provides only limited support for +spawning child processes on Windows. In particular, PHP does not allow accessing +standard I/O pipes on Windows without blocking. As such, this project will not +allow constructing a child process with the default process pipes and will +instead throw a `LogicException` on Windows by default: + +```php +// throws LogicException on Windows +$process = new Process('ping example.com'); +$process->start(); +``` + +There are a number of alternatives and workarounds as detailed below if you want +to run a child process on Windows, each with its own set of pros and cons: + +* As of PHP 8, you can start the child process with `socket` pair descriptors + in place of normal standard I/O pipes like this: + + ```php + $process = new Process( + 'ping example.com', + null, + null, + [ + ['socket'], + ['socket'], + ['socket'] + ] + ); + $process->start(); + + $process->stdout->on('data', function ($chunk) { + echo $chunk; + }); + ``` + + These `socket` pairs support non-blocking process I/O on any platform, + including Windows. However, not all programs accept stdio sockets. + +* This package does work on + [`Windows Subsystem for Linux`](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux) + (or WSL) without issues. When you are in control over how your application is + deployed, we recommend [installing WSL](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide) + when you want to run this package on Windows. + +* If you only care about the exit code of a child process to check if its + execution was successful, you can use [custom pipes](#custom-pipes) to omit + any standard I/O pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array()); + $process->start(); + + $process->on('exit', function ($exitcode) { + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Similarly, this is also useful if your child process communicates over + sockets with remote servers or even your parent process using the + [Socket component](https://github.com/reactphp/socket). This is usually + considered the best alternative if you have control over how your child + process communicates with the parent process. + +* If you only care about command output after the child process has been + executed, you can use [custom pipes](#custom-pipes) to configure file + handles to be passed to the child process instead of pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array( + array('file', 'nul', 'r'), + $stdout = tmpfile(), + array('file', 'nul', 'w') + )); + $process->start(); + + $process->on('exit', function ($exitcode) use ($stdout) { + echo 'exit with ' . $exitcode . PHP_EOL; + + // rewind to start and then read full file (demo only, this is blocking). + // reading from shared file is only safe if you have some synchronization in place + // or after the child process has terminated. + rewind($stdout); + echo stream_get_contents($stdout); + fclose($stdout); + }); + ``` + + Note that this example uses `tmpfile()`/`fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also the [Filesystem component](https://github.com/reactphp/filesystem) as an + alternative. + +* If you want to access command output as it happens in a streaming fashion, + you can use redirection to spawn an additional process to forward your + standard I/O streams to a socket and use [custom pipes](#custom-pipes) to + omit any actual standard I/O pipes like this: + + ```php + $server = new React\Socket\Server('127.0.0.1:0'); + $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->on('data', function ($chunk) { + echo $chunk; + }); + }); + + $command = 'ping example.com | foobar ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start(); + + $process->on('exit', function ($exitcode) use ($server) { + $server->close(); + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Note how this will spawn another fictional `foobar` helper program to consume + the standard output from the actual child process. This is in fact similar + to the above recommendation of using socket connections in the child process, + but in this case does not require modification of the actual child process. + + In this example, the fictional `foobar` helper program can be implemented by + simply consuming all data from standard input and forwarding it to a socket + connection like this: + + ```php + $socket = stream_socket_client($argv[1]); + do { + fwrite($socket, $data = fread(STDIN, 8192)); + } while (isset($data[0])); + ``` + + Accordingly, this example can also be run with plain PHP without having to + rely on any external helper program like this: + + ```php + $code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));'; + $command = 'ping example.com | php -r ' . escapeshellarg($code) . ' ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start(); + ``` + + See also [example #23](examples/23-forward-socket.php). + + Note that this is for illustration purposes only and you may want to implement + some proper error checks and/or socket verification in actual production use + if you do not want to risk other processes connecting to the server socket. + In this case, we suggest looking at the excellent + [createprocess-windows](https://github.com/cubiclesoft/createprocess-windows). + +Additionally, note that the [command](#command) given to the `Process` will be +passed to the underlying Windows-API +([`CreateProcess`](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa)) +as-is and the process will not be launched in a wrapping shell by default. In +particular, this means that shell built-in functions such as `echo hello` or +`sleep 10` may have to be prefixed with an explicit shell command like this: + +```php +$process = new Process('cmd /c echo hello', null, null, $pipes); +$process->start(); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This will install the latest supported version: + +```bash +composer require react/child-process:^0.6.7 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +See above note for limited [Windows Compatibility](#windows-compatibility). + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/trilhas_poo/vendor/react/child-process/composer.json b/trilhas_poo/vendor/react/child-process/composer.json new file mode 100644 index 0000000..fba70b8 --- /dev/null +++ b/trilhas_poo/vendor/react/child-process/composer.json @@ -0,0 +1,49 @@ +{ + "name": "react/child-process", + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": ["process", "event-driven", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "react/event-loop": "^1.2", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/socket": "^1.16", + "sebastian/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "autoload": { + "psr-4": { + "React\\ChildProcess\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\ChildProcess\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/child-process/src/Process.php b/trilhas_poo/vendor/react/child-process/src/Process.php new file mode 100644 index 0000000..aa172af --- /dev/null +++ b/trilhas_poo/vendor/react/child-process/src/Process.php @@ -0,0 +1,585 @@ +start(); + * + * $process->on('exit', function ($code, $term) { + * if ($term === null) { + * echo 'exit with code ' . $code . PHP_EOL; + * } else { + * echo 'terminated with signal ' . $term . PHP_EOL; + * } + * }); + * ``` + * + * Note that `$code` is `null` if the process has terminated, but the exit + * code could not be determined (for example + * [sigchild compatibility](#sigchild-compatibility) was disabled). + * Similarly, `$term` is `null` unless the process has terminated in response to + * an uncaught signal sent to it. + * This is not a limitation of this project, but actual how exit codes and signals + * are exposed on POSIX systems, for more details see also + * [here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). + * + * It's also worth noting that process termination depends on all file descriptors + * being closed beforehand. + * This means that all [process pipes](#stream-properties) will emit a `close` + * event before the `exit` event and that no more `data` events will arrive after + * the `exit` event. + * Accordingly, if either of these pipes is in a paused state (`pause()` method + * or internally due to a `pipe()` call), this detection may not trigger. + */ +class Process extends EventEmitter +{ + /** + * @var WritableStreamInterface|null|DuplexStreamInterface|ReadableStreamInterface + */ + public $stdin; + + /** + * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface + */ + public $stdout; + + /** + * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface + */ + public $stderr; + + /** + * Array with all process pipes (once started) + * + * Unless explicitly configured otherwise during construction, the following + * standard I/O pipes will be assigned by default: + * - 0: STDIN (`WritableStreamInterface`) + * - 1: STDOUT (`ReadableStreamInterface`) + * - 2: STDERR (`ReadableStreamInterface`) + * + * @var array + */ + public $pipes = array(); + + private $cmd; + private $cwd; + private $env; + private $fds; + + private $enhanceSigchildCompatibility; + private $sigchildPipe; + + private $process; + private $status; + private $exitCode; + private $fallbackExitCode; + private $stopSignal; + private $termSignal; + + private static $sigchild; + + /** + * Constructor. + * + * @param string $cmd Command line to run + * @param null|string $cwd Current working directory or null to inherit + * @param null|array $env Environment variables or null to inherit + * @param null|array $fds File descriptors to allocate for this process (or null = default STDIO streams) + * @throws \LogicException On windows or when proc_open() is not installed + */ + public function __construct($cmd, $cwd = null, $env = null, $fds = null) + { + if ($env !== null && !\is_array($env)) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #3 ($env) expected null|array'); + } + if ($fds !== null && !\is_array($fds)) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #4 ($fds) expected null|array'); + } + if (!\function_exists('proc_open')) { + throw new \LogicException('The Process class relies on proc_open(), which is not available on your PHP installation.'); + } + + $this->cmd = $cmd; + $this->cwd = $cwd; + + if (null !== $env) { + $this->env = array(); + foreach ($env as $key => $value) { + $this->env[(string) $key] = (string) $value; + } + } + + if ($fds === null) { + $fds = array( + array('pipe', 'r'), // stdin + array('pipe', 'w'), // stdout + array('pipe', 'w'), // stderr + ); + } + + if (\DIRECTORY_SEPARATOR === '\\') { + foreach ($fds as $fd) { + if (isset($fd[0]) && $fd[0] === 'pipe') { + throw new \LogicException('Process pipes are not supported on Windows due to their blocking nature on Windows'); + } + } + } + + $this->fds = $fds; + $this->enhanceSigchildCompatibility = self::isSigchildEnabled(); + } + + /** + * Start the process. + * + * After the process is started, the standard I/O streams will be constructed + * and available via public properties. + * + * This method takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this process. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * @param ?LoopInterface $loop Loop interface for stream construction + * @param float $interval Interval to periodically monitor process state (seconds) + * @throws \RuntimeException If the process is already running or fails to start + */ + public function start($loop = null, $interval = 0.1) + { + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #1 ($loop) expected null|React\EventLoop\LoopInterface'); + } + if ($this->isRunning()) { + throw new \RuntimeException('Process is already running'); + } + + $loop = $loop ?: Loop::get(); + $cmd = $this->cmd; + $fdSpec = $this->fds; + $sigchild = null; + + // Read exit code through fourth pipe to work around --enable-sigchild + if ($this->enhanceSigchildCompatibility) { + $fdSpec[] = array('pipe', 'w'); + \end($fdSpec); + $sigchild = \key($fdSpec); + + // make sure this is fourth or higher (do not mess with STDIO) + if ($sigchild < 3) { + $fdSpec[3] = $fdSpec[$sigchild]; + unset($fdSpec[$sigchild]); + $sigchild = 3; + } + + $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); + } + + // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs + // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests + $options = array(); + if (\DIRECTORY_SEPARATOR === '\\') { + $options['bypass_shell'] = true; + $options['suppress_errors'] = true; + } + + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errstr) { + // Match errstr from PHP's warning message. + // proc_open(/dev/does-not-exist): Failed to open stream: No such file or directory + $errstr = $error; + }); + + $pipes = array(); + $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); + + \restore_error_handler(); + + if (!\is_resource($this->process)) { + throw new \RuntimeException('Unable to launch a new process: ' . $errstr); + } + + // count open process pipes and await close event for each to drain buffers before detecting exit + $that = $this; + $closeCount = 0; + $streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) { + $closeCount--; + + if ($closeCount > 0) { + return; + } + + // process already closed => report immediately + if (!$that->isRunning()) { + $that->close(); + $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); + return; + } + + // close not detected immediately => check regularly + $loop->addPeriodicTimer($interval, function ($timer) use ($that, $loop) { + if (!$that->isRunning()) { + $loop->cancelTimer($timer); + $that->close(); + $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); + } + }); + }; + + if ($sigchild !== null) { + $this->sigchildPipe = $pipes[$sigchild]; + unset($pipes[$sigchild]); + } + + foreach ($pipes as $n => $fd) { + // use open mode from stream meta data or fall back to pipe open mode for legacy HHVM + $meta = \stream_get_meta_data($fd); + $mode = $meta['mode'] === '' ? ($this->fds[$n][1] === 'r' ? 'w' : 'r') : $meta['mode']; + + if ($mode === 'r+') { + $stream = new DuplexResourceStream($fd, $loop); + $stream->on('close', $streamCloseHandler); + $closeCount++; + } elseif ($mode === 'w') { + $stream = new WritableResourceStream($fd, $loop); + } else { + $stream = new ReadableResourceStream($fd, $loop); + $stream->on('close', $streamCloseHandler); + $closeCount++; + } + $this->pipes[$n] = $stream; + } + + $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; + $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; + $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; + + // immediately start checking for process exit when started without any I/O pipes + if (!$closeCount) { + $streamCloseHandler(); + } + } + + /** + * Close the process. + * + * This method should only be invoked via the periodic timer that monitors + * the process state. + */ + public function close() + { + if ($this->process === null) { + return; + } + + foreach ($this->pipes as $pipe) { + $pipe->close(); + } + + if ($this->enhanceSigchildCompatibility) { + $this->pollExitCodePipe(); + $this->closeExitCodePipe(); + } + + $exitCode = \proc_close($this->process); + $this->process = null; + + if ($this->exitCode === null && $exitCode !== -1) { + $this->exitCode = $exitCode; + } + + if ($this->exitCode === null && $this->status['exitcode'] !== -1) { + $this->exitCode = $this->status['exitcode']; + } + + if ($this->exitCode === null && $this->fallbackExitCode !== null) { + $this->exitCode = $this->fallbackExitCode; + $this->fallbackExitCode = null; + } + } + + /** + * Terminate the process with an optional signal. + * + * @param int $signal Optional signal (default: SIGTERM) + * @return bool Whether the signal was sent successfully + */ + public function terminate($signal = null) + { + if ($this->process === null) { + return false; + } + + if ($signal !== null) { + return \proc_terminate($this->process, $signal); + } + + return \proc_terminate($this->process); + } + + /** + * Get the command string used to launch the process. + * + * @return string + */ + public function getCommand() + { + return $this->cmd; + } + + /** + * Get the exit code returned by the process. + * + * This value is only meaningful if isRunning() has returned false. Null + * will be returned if the process is still running. + * + * Null may also be returned if the process has terminated, but the exit + * code could not be determined (e.g. sigchild compatibility was disabled). + * + * @return int|null + */ + public function getExitCode() + { + return $this->exitCode; + } + + /** + * Get the process ID. + * + * @return int|null + */ + public function getPid() + { + $status = $this->getCachedStatus(); + + return $status !== null ? $status['pid'] : null; + } + + /** + * Get the signal that caused the process to stop its execution. + * + * This value is only meaningful if isStopped() has returned true. Null will + * be returned if the process was never stopped. + * + * @return int|null + */ + public function getStopSignal() + { + return $this->stopSignal; + } + + /** + * Get the signal that caused the process to terminate its execution. + * + * This value is only meaningful if isTerminated() has returned true. Null + * will be returned if the process was never terminated. + * + * @return int|null + */ + public function getTermSignal() + { + return $this->termSignal; + } + + /** + * Return whether the process is still running. + * + * @return bool + */ + public function isRunning() + { + if ($this->process === null) { + return false; + } + + $status = $this->getFreshStatus(); + + return $status !== null ? $status['running'] : false; + } + + /** + * Return whether the process has been stopped by a signal. + * + * @return bool + */ + public function isStopped() + { + $status = $this->getFreshStatus(); + + return $status !== null ? $status['stopped'] : false; + } + + /** + * Return whether the process has been terminated by an uncaught signal. + * + * @return bool + */ + public function isTerminated() + { + $status = $this->getFreshStatus(); + + return $status !== null ? $status['signaled'] : false; + } + + /** + * Return whether PHP has been compiled with the '--enable-sigchild' option. + * + * @see \Symfony\Component\Process\Process::isSigchildEnabled() + * @return bool + */ + public final static function isSigchildEnabled() + { + if (null !== self::$sigchild) { + return self::$sigchild; + } + + if (!\function_exists('phpinfo')) { + return self::$sigchild = false; // @codeCoverageIgnore + } + + \ob_start(); + \phpinfo(INFO_GENERAL); + + return self::$sigchild = false !== \strpos(\ob_get_clean(), '--enable-sigchild'); + } + + /** + * Enable or disable sigchild compatibility mode. + * + * Sigchild compatibility mode is required to get the exit code and + * determine the success of a process when PHP has been compiled with + * the --enable-sigchild option. + * + * @param bool $sigchild + * @return void + */ + public final static function setSigchildEnabled($sigchild) + { + self::$sigchild = (bool) $sigchild; + } + + /** + * Check the fourth pipe for an exit code. + * + * This should only be used if --enable-sigchild compatibility was enabled. + */ + private function pollExitCodePipe() + { + if ($this->sigchildPipe === null) { + return; + } + + $r = array($this->sigchildPipe); + $w = $e = null; + + $n = @\stream_select($r, $w, $e, 0); + + if (1 !== $n) { + return; + } + + $data = \fread($r[0], 8192); + + if (\strlen($data) > 0) { + $this->fallbackExitCode = (int) $data; + } + } + + /** + * Close the fourth pipe used to relay an exit code. + * + * This should only be used if --enable-sigchild compatibility was enabled. + */ + private function closeExitCodePipe() + { + if ($this->sigchildPipe === null) { + return; + } + + \fclose($this->sigchildPipe); + $this->sigchildPipe = null; + } + + /** + * Return the cached process status. + * + * @return array + */ + private function getCachedStatus() + { + if ($this->status === null) { + $this->updateStatus(); + } + + return $this->status; + } + + /** + * Return the updated process status. + * + * @return array + */ + private function getFreshStatus() + { + $this->updateStatus(); + + return $this->status; + } + + /** + * Update the process status, stop/term signals, and exit code. + * + * Stop/term signals are only updated if the process is currently stopped or + * signaled, respectively. Otherwise, signal values will remain as-is so the + * corresponding getter methods may be used at a later point in time. + */ + private function updateStatus() + { + if ($this->process === null) { + return; + } + + $this->status = \proc_get_status($this->process); + + if ($this->status === false) { + throw new \UnexpectedValueException('proc_get_status() failed'); + } + + if ($this->status['stopped']) { + $this->stopSignal = $this->status['stopsig']; + } + + if ($this->status['signaled']) { + $this->termSignal = $this->status['termsig']; + } + + if (!$this->status['running'] && -1 !== $this->status['exitcode']) { + $this->exitCode = $this->status['exitcode']; + } + } +} diff --git a/trilhas_poo/vendor/react/dns/CHANGELOG.md b/trilhas_poo/vendor/react/dns/CHANGELOG.md new file mode 100644 index 0000000..3064849 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/CHANGELOG.md @@ -0,0 +1,460 @@ +# Changelog + +## 1.14.0 (2025-11-18) + +* Feature: Improve PHP 8.5+ support by avoiding deprecated `setAccessible()` calls. + (#238 by @W0rma and #243 by @WyriHaximus) + +* Improve test suite, update test environment and increase query count in excessive TCP query tests. + (#239 and #240 by @WyriHaximus) + +## 1.13.0 (2024-06-13) + +* Feature: Improve PHP 8.4+ support by avoiding implicitly nullable type declarations. + (#224 by @WyriHaximus) + +## 1.12.0 (2023-11-29) + +* Feature: Full PHP 8.3 compatibility. + (#217 by @sergiy-petrov) + +* Update test environment and avoid unhandled promise rejections. + (#215, #216 and #218 by @clue) + +## 1.11.0 (2023-06-02) + +* Feature: Include timeout logic to avoid dependency on reactphp/promise-timer. + (#213 by @clue) + +* Improve test suite and project setup and report failed assertions. + (#210 by @clue, #212 by @WyriHaximus and #209 and #211 by @SimonFrings) + +## 1.10.0 (2022-09-08) + +* Feature: Full support for PHP 8.2 release. + (#201 by @clue and #207 by @WyriHaximus) + +* Feature: Optimize forward compatibility with Promise v3, avoid hitting autoloader. + (#202 by @clue) + +* Feature / Fix: Improve error reporting when custom error handler is used. + (#197 by @clue) + +* Fix: Fix invalid references in exception stack trace. + (#191 by @clue) + +* Minor documentation improvements. + (#195 by @SimonFrings and #203 by @nhedger) + +* Improve test suite, update to use default loop and new reactphp/async package. + (#204, #205 and #206 by @clue and #196 by @SimonFrings) + +## 1.9.0 (2021-12-20) + +* Feature: Full support for PHP 8.1 release and prepare PHP 8.2 compatibility + by refactoring `Parser` to avoid assigning dynamic properties. + (#188 and #186 by @clue and #184 by @SimonFrings) + +* Feature: Avoid dependency on `ext-filter`. + (#185 by @clue) + +* Feature / Fix: Skip invalid nameserver entries from `resolv.conf` and ignore IPv6 zone IDs. + (#187 by @clue) + +* Feature / Fix: Reduce socket read chunk size for queries over TCP/IP. + (#189 by @clue) + +## 1.8.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#182 by @clue) + + ```php + // old (still supported) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config, $loop); + + // new (using default loop) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config); + ``` + +## 1.7.0 (2021-06-25) + +* Feature: Update DNS `Factory` to accept complete `Config` object. + Add new `FallbackExecutor` and use fallback DNS servers when `Config` lists multiple servers. + (#179 and #180 by @clue) + + ```php + // old (still supported) + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + $resolver = $factory->create($server, $loop); + + // new + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; + } + $resolver = $factory->create($config, $loop); + ``` + +## 1.6.0 (2021-06-21) + +* Feature: Add support for legacy `SPF` record type. + (#178 by @akondas and @clue) + +* Fix: Fix integer overflow for TCP/IP chunk size on 32 bit platforms. + (#177 by @clue) + +## 1.5.0 (2021-03-05) + +* Feature: Improve error reporting when query fails, include domain and query type and DNS server address where applicable. + (#174 by @clue) + +* Feature: Improve error handling when sending data to DNS server fails (macOS). + (#171 and #172 by @clue) + +* Fix: Improve DNS response parser to limit recursion for compressed labels. + (#169 by @clue) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#170 by @SimonFrings) + +## 1.4.0 (2020-09-18) + +* Feature: Support upcoming PHP 8. + (#168 by @clue) + +* Improve test suite and update to PHPUnit 9.3. + (#164 by @clue, #165 and #166 by @SimonFrings and #167 by @WyriHaximus) + +## 1.3.0 (2020-07-10) + +* Feature: Forward compatibility with react/promise v3. + (#153 by @WyriHaximus) + +* Feature: Support parsing `OPT` records (EDNS0). + (#157 by @clue) + +* Fix: Avoid PHP warnings due to lack of args in exception trace on PHP 7.4. + (#160 by @clue) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9 and PHP 7.4 and clean up test suite. + (#154 by @reedy, #156 by @clue and #163 by @SimonFrings) + +## 1.2.0 (2019-08-15) + +* Feature: Add `TcpTransportExecutor` to send DNS queries over TCP/IP connection, + add `SelectiveTransportExecutor` to retry with TCP if UDP is truncated and + automatically select transport protocol when no explicit `udp://` or `tcp://` scheme is given in `Factory`. + (#145, #146, #147 and #148 by @clue) + +* Feature: Support escaping literal dots and special characters in domain names. + (#144 by @clue) + +## 1.1.0 (2019-07-18) + +* Feature: Support parsing `CAA` and `SSHFP` records. + (#141 and #142 by @clue) + +* Feature: Add `ResolverInterface` as common interface for `Resolver` class. + (#139 by @clue) + +* Fix: Add missing private property definitions and + remove unneeded dependency on `react/stream`. + (#140 and #143 by @clue) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +This update involves a number of BC breaks due to dropped support for +deprecated functionality and some internal API cleanup. We've tried hard to +avoid BC breaks where possible and minimize impact otherwise. We expect that +most consumers of this package will actually not be affected by any BC +breaks, see below for more details: + +* BC break: Delete all deprecated APIs, use `Query` objects for `Message` questions + instead of nested arrays and increase code coverage to 100%. + (#130 by @clue) + +* BC break: Move `$nameserver` from `ExecutorInterface` to `UdpTransportExecutor`, + remove advanced/internal `UdpTransportExecutor` args for `Parser`/`BinaryDumper` and + add API documentation for `ExecutorInterface`. + (#135, #137 and #138 by @clue) + +* BC break: Replace `HeaderBag` attributes with simple `Message` properties. + (#132 by @clue) + +* BC break: Mark all `Record` attributes as required, add documentation vs `Query`. + (#136 by @clue) + +* BC break: Mark all classes as final to discourage inheritance + (#134 by @WyriHaximus) + +## 0.4.19 (2019-07-10) + +* Feature: Avoid garbage references when DNS resolution rejects on legacy PHP <= 5.6. + (#133 by @clue) + +## 0.4.18 (2019-09-07) + +* Feature / Fix: Implement `CachingExecutor` using cache TTL, deprecate old `CachedExecutor`, + respect TTL from response records when caching and do not cache truncated responses. + (#129 by @clue) + +* Feature: Limit cache size to 256 last responses by default. + (#127 by @clue) + +* Feature: Cooperatively resolve hosts to avoid running same query concurrently. + (#125 by @clue) + +## 0.4.17 (2019-04-01) + +* Feature: Support parsing `authority` and `additional` records from DNS response. + (#123 by @clue) + +* Feature: Support dumping records as part of outgoing binary DNS message. + (#124 by @clue) + +* Feature: Forward compatibility with upcoming Cache v0.6 and Cache v1.0 + (#121 by @clue) + +* Improve test suite to add forward compatibility with PHPUnit 7, + test against PHP 7.3 and use legacy PHPUnit 5 on legacy HHVM. + (#122 by @clue) + +## 0.4.16 (2018-11-11) + +* Feature: Improve promise cancellation for DNS lookup retries and clean up any garbage references. + (#118 by @clue) + +* Fix: Reject parsing malformed DNS response messages such as incomplete DNS response messages, + malformed record data or malformed compressed domain name labels. + (#115 and #117 by @clue) + +* Fix: Fix interpretation of TTL as UINT32 with most significant bit unset. + (#116 by @clue) + +* Fix: Fix caching advanced MX/SRV/TXT/SOA structures. + (#112 by @clue) + +## 0.4.15 (2018-07-02) + +* Feature: Add `resolveAll()` method to support custom query types in `Resolver`. + (#110 by @clue and @WyriHaximus) + + ```php + $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + }); + ``` + +* Feature: Support parsing `NS`, `TXT`, `MX`, `SOA` and `SRV` records. + (#104, #105, #106, #107 and #108 by @clue) + +* Feature: Add support for `Message::TYPE_ANY` and parse unknown types as binary data. + (#104 by @clue) + +* Feature: Improve error messages for failed queries and improve documentation. + (#109 by @clue) + +* Feature: Add reverse DNS lookup example. + (#111 by @clue) + +## 0.4.14 (2018-06-26) + +* Feature: Add `UdpTransportExecutor`, validate incoming DNS response messages + to avoid cache poisoning attacks and deprecate legacy `Executor`. + (#101 and #103 by @clue) + +* Feature: Forward compatibility with Cache 0.5 + (#102 by @clue) + +* Deprecate legacy `Query::$currentTime` and binary parser data attributes to clean up and simplify API. + (#99 by @clue) + +## 0.4.13 (2018-02-27) + +* Add `Config::loadSystemConfigBlocking()` to load default system config + and support parsing DNS config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac and WMIC on Windows) + (#92, #93, #94 and #95 by @clue) + + ```php + $config = Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + ``` + +* Remove unneeded cyclic dependency on react/socket + (#96 by @clue) + +## 0.4.12 (2018-01-14) + +* Improve test suite by adding forward compatibility with PHPUnit 6, + test against PHP 7.2, fix forward compatibility with upcoming EventLoop releases, + add test group to skip integration tests relying on internet connection + and add minor documentation improvements. + (#85 and #87 by @carusogabriel, #88 and #89 by @clue and #83 by @jsor) + +## 0.4.11 (2017-08-25) + +* Feature: Support resolving from default hosts file + (#75, #76 and #77 by @clue) + + This means that resolving hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $resolver->resolve('localhost')->then(function ($ip) { + echo 'IP: ' . $ip; + }); + ``` + + The new `HostsExecutor` exists for advanced usage and is otherwise used + internally for this feature. + +## 0.4.10 (2017-08-10) + +* Feature: Forward compatibility with EventLoop v1.0 and v0.5 and + lock minimum dependencies and work around circular dependency for tests + (#70 and #71 by @clue) + +* Fix: Work around DNS timeout issues for Windows users + (#74 by @clue) + +* Documentation and examples for advanced usage + (#66 by @WyriHaximus) + +* Remove broken TCP code, do not retry with invalid TCP query + (#73 by @clue) + +* Improve test suite by fixing HHVM build for now again and ignore future HHVM build errors and + lock Travis distro so new defaults will not break the build and + fix failing tests for PHP 7.1 + (#68 by @WyriHaximus and #69 and #72 by @clue) + +## 0.4.9 (2017-05-01) + +* Feature: Forward compatibility with upcoming Socket v1.0 and v0.8 + (#61 by @clue) + +## 0.4.8 (2017-04-16) + +* Feature: Add support for the AAAA record type to the protocol parser + (#58 by @othillo) + +* Feature: Add support for the PTR record type to the protocol parser + (#59 by @othillo) + +## 0.4.7 (2017-03-31) + +* Feature: Forward compatibility with upcoming Socket v0.6 and v0.7 component + (#57 by @clue) + +## 0.4.6 (2017-03-11) + +* Fix: Fix DNS timeout issues for Windows users and add forward compatibility + with Stream v0.5 and upcoming v0.6 + (#53 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` + (#54 by @clue) + +## 0.4.5 (2017-03-02) + +* Fix: Ensure we ignore the case of the answer + (#51 by @WyriHaximus) + +* Feature: Add `TimeoutExecutor` and simplify internal APIs to allow internal + code re-use for upcoming versions. + (#48 and #49 by @clue) + +## 0.4.4 (2017-02-13) + +* Fix: Fix handling connection and stream errors + (#45 by @clue) + +* Feature: Add examples and forward compatibility with upcoming Socket v0.5 component + (#46 and #47 by @clue) + +## 0.4.3 (2016-07-31) + +* Feature: Allow for cache adapter injection (#38 by @WyriHaximus) + + ```php + $factory = new React\Dns\Resolver\Factory(); + + $cache = new MyCustomCacheInstance(); + $resolver = $factory->createCached('8.8.8.8', $loop, $cache); + ``` + +* Feature: Support Promise cancellation (#35 by @clue) + + ```php + $promise = $resolver->resolve('reactphp.org'); + + $promise->cancel(); + ``` + +## 0.4.2 (2016-02-24) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#34 by @clue) +* Adjust compatibility to 5.3 (#30 by @clue) + +## 0.4.1 (2014-04-13) + +* Bug fix: Fixed PSR-4 autoload path (@marcj/WyriHaximus) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Bug fix: Properly resolve CNAME aliases +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.2 (2013-05-10) + +* Feature: Support default port for IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS + +## 0.2.5 (2012-11-26) + +* Version bump + +## 0.2.4 (2012-11-18) + +* Feature: Change to promise-based API (@jsor) + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Feature: DNS executor timeout handling (@arnaud-lb) +* Feature: DNS retry executor (@arnaud-lb) + +## 0.2.1 (2012-10-14) + +* Minor adjustments to DNS parser + +## 0.2.0 (2012-09-10) + +* Feature: DNS resolver diff --git a/trilhas_poo/vendor/react/dns/LICENSE b/trilhas_poo/vendor/react/dns/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/dns/README.md b/trilhas_poo/vendor/react/dns/README.md new file mode 100644 index 0000000..b6e8fe4 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/README.md @@ -0,0 +1,453 @@ +# DNS + +[![CI status](https://github.com/reactphp/dns/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/dns/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/dns?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/dns) + +Async DNS resolver for [ReactPHP](https://reactphp.org/). + +The main point of the DNS component is to provide async DNS resolution. +However, it is really a toolkit for working with DNS messages, and could +easily be used to create a DNS server. + +**Table of contents** + +* [Basic usage](#basic-usage) +* [Caching](#caching) + * [Custom cache adapter](#custom-cache-adapter) +* [ResolverInterface](#resolverinterface) + * [resolve()](#resolve) + * [resolveAll()](#resolveall) +* [Advanced usage](#advanced-usage) + * [UdpTransportExecutor](#udptransportexecutor) + * [TcpTransportExecutor](#tcptransportexecutor) + * [SelectiveTransportExecutor](#selectivetransportexecutor) + * [HostsFileExecutor](#hostsfileexecutor) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [References](#references) + +## Basic usage + +The most basic usage is to just create a resolver through the resolver +factory. All you need to give it is a nameserver, then you can start resolving +names, baby! + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->create($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +See also the [first example](examples). + +The `Config` class can be used to load the system default config. This is an +operation that may access the filesystem and block. Ideally, this method should +thus be executed only once before the loop starts and not repeatedly while it is +running. +Note that this class may return an *empty* configuration if the system config +can not be loaded. As such, you'll likely want to apply a default nameserver +as above if none can be found. + +> Note that the factory loads the hosts file from the filesystem once when + creating the resolver instance. + Ideally, this method should thus be executed only once before the loop starts + and not repeatedly while it is running. + +But there's more. + +## Caching + +You can cache results by configuring the resolver to use a `CachedExecutor`: + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); + +... + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +If the first call returns before the second, only one query will be executed. +The second result will be served from an in memory cache. +This is particularly useful for long running scripts where the same hostnames +have to be looked up multiple times. + +See also the [third example](examples). + +### Custom cache adapter + +By default, the above will use an in memory cache. + +You can also specify a custom cache implementing [`CacheInterface`](https://github.com/reactphp/cache) to handle the record cache instead: + +```php +$cache = new React\Cache\ArrayCache(); +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached('8.8.8.8', null, $cache); +``` + +See also the wiki for possible [cache implementations](https://github.com/reactphp/react/wiki/Users#cache-implementations). + +## ResolverInterface + + + +### resolve() + +The `resolve(string $domain): PromiseInterface` method can be used to +resolve the given $domain name to a single IPv4 address (type `A` query). + +```php +$resolver->resolve('reactphp.org')->then(function ($ip) { + echo 'IP for reactphp.org is ' . $ip . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a single IP +address on success. + +If the DNS server sends a DNS response message that contains more than +one IP address for this query, it will randomly pick one of the IP +addresses from the response. If you want the full list of IP addresses +or want to send a different type of query, you should use the +[`resolveAll()`](#resolveall) method instead. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolve('reactphp.org'); + +$promise->cancel(); +``` + +### resolveAll() + +The `resolveAll(string $host, int $type): PromiseInterface` method can be used to +resolve all record values for the given $domain name and query $type. + +```php +$resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); + +$resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a list with all +record values on success. + +If the DNS server sends a DNS response message that contains one or more +records for this query, it will return a list with all record values +from the response. You can use the `Message::TYPE_*` constants to control +which type of query will be sent. Note that this method always returns a +list of record values, but each record value type depends on the query +type. For example, it returns the IPv4 addresses for type `A` queries, +the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, +`CNAME` and `PTR` queries and structured data for other queries. See also +the `Record` documentation for more details. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + +$promise->cancel(); +``` + +## Advanced Usage + +### UdpTransportExecutor + +The `UdpTransportExecutor` can be used to +send DNS queries over a UDP transport. + +This is the main class that sends a DNS query to your DNS server and is used +internally by the `Resolver` for the actual message transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `igor.io`. + +```php +$executor = new UdpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also the [fourth example](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 +); +``` + +Also note that this executor uses an unreliable UDP transport and that it +does not implement any retry logic, so you will likely want to use this in +combination with a `RetryExecutor` like this: + +```php +$executor = new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) + ) +); +``` + +> Internally, this class uses PHP's UDP sockets and does not take advantage + of [react/datagram](https://github.com/reactphp/datagram) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Datagram + component instead of reimplementing this socket logic from scratch. + +### TcpTransportExecutor + +The `TcpTransportExecutor` class can be used to +send DNS queries over a TCP/IP stream transport. + +This is one of the main classes that send a DNS query to your DNS server. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new TcpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also [example #92](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 +); +``` + +Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP +transport, so you do not necessarily have to implement any retry logic. + +Note that this executor is entirely async and as such allows you to execute +queries concurrently. The first query will establish a TCP/IP socket +connection to the DNS server which will be kept open for a short period. +Additional queries will automatically reuse this existing socket connection +to the DNS server, will pipeline multiple requests over this single +connection and will keep an idle connection open for a short period. The +initial TCP/IP connection overhead may incur a slight delay if you only send +occasional queries – when sending a larger number of concurrent queries over +an existing connection, it becomes increasingly more efficient and avoids +creating many concurrent sockets like the UDP-based executor. You may still +want to limit the number of (concurrent) queries in your application or you +may be facing rate limitations and bans on the resolver end. For many common +applications, you may want to avoid sending the same query multiple times +when the first one is still pending, so you will likely want to use this in +combination with a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +> Internally, this class uses PHP's TCP/IP sockets and does not take advantage + of [react/socket](https://github.com/reactphp/socket) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Socket + component instead of reimplementing this socket logic from scratch. + +### SelectiveTransportExecutor + +The `SelectiveTransportExecutor` class can be used to +Send DNS queries over a UDP or TCP/IP stream transport. + +This class will automatically choose the correct transport protocol to send +a DNS query to your DNS server. It will always try to send it over the more +efficient UDP transport first. If this query yields a size related issue +(truncated messages), it will retry over a streaming TCP/IP transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new SelectiveTransportExecutor($udpExecutor, $tcpExecutor); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +Note that this executor only implements the logic to select the correct +transport for the given DNS query. Implementing the correct transport logic, +implementing timeouts and any retry logic is left up to the given executors, +see also [`UdpTransportExecutor`](#udptransportexecutor) and +[`TcpTransportExecutor`](#tcptransportexecutor) for more details. + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new SelectiveTransportExecutor( + $datagramExecutor, + $streamExecutor + ) +); +``` + +### HostsFileExecutor + +Note that the above `UdpTransportExecutor` class always performs an actual DNS query. +If you also want to take entries from your hosts file into account, you may +use this code: + +```php +$hosts = \React\Dns\Config\HostsFile::loadFromPathBlocking(); + +$executor = new UdpTransportExecutor('8.8.8.8:53'); +$executor = new HostsFileExecutor($hosts, $executor); + +$executor->query( + new Query('localhost', Message::TYPE_A, Message::CLASS_IN) +); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/dns:^1.14 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## References + +* [RFC 1034](https://tools.ietf.org/html/rfc1034) Domain Names - Concepts and Facilities +* [RFC 1035](https://tools.ietf.org/html/rfc1035) Domain Names - Implementation and Specification diff --git a/trilhas_poo/vendor/react/dns/composer.json b/trilhas_poo/vendor/react/dns/composer.json new file mode 100644 index 0000000..4fe5c0d --- /dev/null +++ b/trilhas_poo/vendor/react/dns/composer.json @@ -0,0 +1,49 @@ +{ + "name": "react/dns", + "description": "Async DNS resolver for ReactPHP", + "keywords": ["dns", "dns-resolver", "ReactPHP", "async"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3 || ^2", + "react/promise-timer": "^1.11" + }, + "autoload": { + "psr-4": { + "React\\Dns\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Dns\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/dns/src/BadServerException.php b/trilhas_poo/vendor/react/dns/src/BadServerException.php new file mode 100644 index 0000000..3d95213 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/BadServerException.php @@ -0,0 +1,7 @@ + `fe80:1`) + if (strpos($ip, ':') !== false && ($pos = strpos($ip, '%')) !== false) { + $ip = substr($ip, 0, $pos); + } + + if (@inet_pton($ip) !== false) { + $config->nameservers[] = $ip; + } + } + + return $config; + } + + /** + * Loads the DNS configurations from Windows's WMIC (from the given command or default command) + * + * Note that this method blocks while loading the given command and should + * thus be used with care! While this should be relatively fast for normal + * WMIC commands, it remains unknown if this may block under certain + * circumstances. In particular, this method should only be executed before + * the loop starts, not while it is running. + * + * Note that this method will only try to execute the given command try to + * parse its output, irrespective of whether this command exists. In + * particular, this command is only available on Windows. Currently, this + * will only parse valid nameserver entries from the command output and will + * ignore all other output without complaining. + * + * Note that the previous section implies that this may return an empty + * `Config` object if no valid nameserver entries can be found. + * + * @param ?string $command (advanced) should not be given (NULL) unless you know what you're doing + * @return self + * @link https://ss64.com/nt/wmic.html + */ + public static function loadWmicBlocking($command = null) + { + $contents = shell_exec($command === null ? 'wmic NICCONFIG get "DNSServerSearchOrder" /format:CSV' : $command); + preg_match_all('/(?<=[{;,"])([\da-f.:]{4,})(?=[};,"])/i', $contents, $matches); + + $config = new self(); + $config->nameservers = $matches[1]; + + return $config; + } + + public $nameservers = array(); +} diff --git a/trilhas_poo/vendor/react/dns/src/Config/HostsFile.php b/trilhas_poo/vendor/react/dns/src/Config/HostsFile.php new file mode 100644 index 0000000..1060231 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Config/HostsFile.php @@ -0,0 +1,153 @@ +contents = $contents; + } + + /** + * Returns all IPs for the given hostname + * + * @param string $name + * @return string[] + */ + public function getIpsForHost($name) + { + $name = strtolower($name); + + $ips = array(); + foreach (preg_split('/\r?\n/', $this->contents) as $line) { + $parts = preg_split('/\s+/', $line); + $ip = array_shift($parts); + if ($parts && array_search($name, $parts) !== false) { + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (strpos($ip, ':') !== false && ($pos = strpos($ip, '%')) !== false) { + $ip = substr($ip, 0, $pos); + } + + if (@inet_pton($ip) !== false) { + $ips[] = $ip; + } + } + } + + return $ips; + } + + /** + * Returns all hostnames for the given IPv4 or IPv6 address + * + * @param string $ip + * @return string[] + */ + public function getHostsForIp($ip) + { + // check binary representation of IP to avoid string case and short notation + $ip = @inet_pton($ip); + if ($ip === false) { + return array(); + } + + $names = array(); + foreach (preg_split('/\r?\n/', $this->contents) as $line) { + $parts = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY); + $addr = (string) array_shift($parts); + + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (strpos($addr, ':') !== false && ($pos = strpos($addr, '%')) !== false) { + $addr = substr($addr, 0, $pos); + } + + if (@inet_pton($addr) === $ip) { + foreach ($parts as $part) { + $names[] = $part; + } + } + } + + return $names; + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Model/Message.php b/trilhas_poo/vendor/react/dns/src/Model/Message.php new file mode 100644 index 0000000..bac2b10 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Model/Message.php @@ -0,0 +1,230 @@ +id = self::generateId(); + $request->rd = true; + $request->questions[] = $query; + + return $request; + } + + /** + * Creates a new response message for the given query with the given answer records + * + * @param Query $query + * @param Record[] $answers + * @return self + */ + public static function createResponseWithAnswersForQuery(Query $query, array $answers) + { + $response = new Message(); + $response->id = self::generateId(); + $response->qr = true; + $response->rd = true; + + $response->questions[] = $query; + + foreach ($answers as $record) { + $response->answers[] = $record; + } + + return $response; + } + + /** + * generates a random 16 bit message ID + * + * This uses a CSPRNG so that an outside attacker that is sending spoofed + * DNS response messages can not guess the message ID to avoid possible + * cache poisoning attacks. + * + * The `random_int()` function is only available on PHP 7+ or when + * https://github.com/paragonie/random_compat is installed. As such, using + * the latest supported PHP version is highly recommended. This currently + * falls back to a less secure random number generator on older PHP versions + * in the hope that this system is properly protected against outside + * attackers, for example by using one of the common local DNS proxy stubs. + * + * @return int + * @see self::getId() + * @codeCoverageIgnore + */ + private static function generateId() + { + if (function_exists('random_int')) { + return random_int(0, 0xffff); + } + return mt_rand(0, 0xffff); + } + + /** + * The 16 bit message ID + * + * The response message ID has to match the request message ID. This allows + * the receiver to verify this is the correct response message. An outside + * attacker may try to inject fake responses by "guessing" the message ID, + * so this should use a proper CSPRNG to avoid possible cache poisoning. + * + * @var int 16 bit message ID + * @see self::generateId() + */ + public $id = 0; + + /** + * @var bool Query/Response flag, query=false or response=true + */ + public $qr = false; + + /** + * @var int specifies the kind of query (4 bit), see self::OPCODE_* constants + * @see self::OPCODE_QUERY + */ + public $opcode = self::OPCODE_QUERY; + + /** + * + * @var bool Authoritative Answer + */ + public $aa = false; + + /** + * @var bool TrunCation + */ + public $tc = false; + + /** + * @var bool Recursion Desired + */ + public $rd = false; + + /** + * @var bool Recursion Available + */ + public $ra = false; + + /** + * @var int response code (4 bit), see self::RCODE_* constants + * @see self::RCODE_OK + */ + public $rcode = Message::RCODE_OK; + + /** + * An array of Query objects + * + * ```php + * $questions = array( + * new Query( + * 'reactphp.org', + * Message::TYPE_A, + * Message::CLASS_IN + * ) + * ); + * ``` + * + * @var Query[] + */ + public $questions = array(); + + /** + * @var Record[] + */ + public $answers = array(); + + /** + * @var Record[] + */ + public $authority = array(); + + /** + * @var Record[] + */ + public $additional = array(); +} diff --git a/trilhas_poo/vendor/react/dns/src/Model/Record.php b/trilhas_poo/vendor/react/dns/src/Model/Record.php new file mode 100644 index 0000000..c20403f --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Model/Record.php @@ -0,0 +1,153 @@ +name = $name; + $this->type = $type; + $this->class = $class; + $this->ttl = $ttl; + $this->data = $data; + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Protocol/BinaryDumper.php b/trilhas_poo/vendor/react/dns/src/Protocol/BinaryDumper.php new file mode 100644 index 0000000..6f4030f --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Protocol/BinaryDumper.php @@ -0,0 +1,199 @@ +headerToBinary($message); + $data .= $this->questionToBinary($message->questions); + $data .= $this->recordsToBinary($message->answers); + $data .= $this->recordsToBinary($message->authority); + $data .= $this->recordsToBinary($message->additional); + + return $data; + } + + /** + * @param Message $message + * @return string + */ + private function headerToBinary(Message $message) + { + $data = ''; + + $data .= pack('n', $message->id); + + $flags = 0x00; + $flags = ($flags << 1) | ($message->qr ? 1 : 0); + $flags = ($flags << 4) | $message->opcode; + $flags = ($flags << 1) | ($message->aa ? 1 : 0); + $flags = ($flags << 1) | ($message->tc ? 1 : 0); + $flags = ($flags << 1) | ($message->rd ? 1 : 0); + $flags = ($flags << 1) | ($message->ra ? 1 : 0); + $flags = ($flags << 3) | 0; // skip unused zero bit + $flags = ($flags << 4) | $message->rcode; + + $data .= pack('n', $flags); + + $data .= pack('n', count($message->questions)); + $data .= pack('n', count($message->answers)); + $data .= pack('n', count($message->authority)); + $data .= pack('n', count($message->additional)); + + return $data; + } + + /** + * @param Query[] $questions + * @return string + */ + private function questionToBinary(array $questions) + { + $data = ''; + + foreach ($questions as $question) { + $data .= $this->domainNameToBinary($question->name); + $data .= pack('n*', $question->type, $question->class); + } + + return $data; + } + + /** + * @param Record[] $records + * @return string + */ + private function recordsToBinary(array $records) + { + $data = ''; + + foreach ($records as $record) { + /* @var $record Record */ + switch ($record->type) { + case Message::TYPE_A: + case Message::TYPE_AAAA: + $binary = \inet_pton($record->data); + break; + case Message::TYPE_CNAME: + case Message::TYPE_NS: + case Message::TYPE_PTR: + $binary = $this->domainNameToBinary($record->data); + break; + case Message::TYPE_TXT: + case Message::TYPE_SPF: + $binary = $this->textsToBinary($record->data); + break; + case Message::TYPE_MX: + $binary = \pack( + 'n', + $record->data['priority'] + ); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SRV: + $binary = \pack( + 'n*', + $record->data['priority'], + $record->data['weight'], + $record->data['port'] + ); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SOA: + $binary = $this->domainNameToBinary($record->data['mname']); + $binary .= $this->domainNameToBinary($record->data['rname']); + $binary .= \pack( + 'N*', + $record->data['serial'], + $record->data['refresh'], + $record->data['retry'], + $record->data['expire'], + $record->data['minimum'] + ); + break; + case Message::TYPE_CAA: + $binary = \pack( + 'C*', + $record->data['flag'], + \strlen($record->data['tag']) + ); + $binary .= $record->data['tag']; + $binary .= $record->data['value']; + break; + case Message::TYPE_SSHFP: + $binary = \pack( + 'CCH*', + $record->data['algorithm'], + $record->data['type'], + $record->data['fingerprint'] + ); + break; + case Message::TYPE_OPT: + $binary = ''; + foreach ($record->data as $opt => $value) { + if ($opt === Message::OPT_TCP_KEEPALIVE && $value !== null) { + $value = \pack('n', round($value * 10)); + } + $binary .= \pack('n*', $opt, \strlen((string) $value)) . $value; + } + break; + default: + // RDATA is already stored as binary value for unknown record types + $binary = $record->data; + } + + $data .= $this->domainNameToBinary($record->name); + $data .= \pack('nnNn', $record->type, $record->class, $record->ttl, \strlen($binary)); + $data .= $binary; + } + + return $data; + } + + /** + * @param string[] $texts + * @return string + */ + private function textsToBinary(array $texts) + { + $data = ''; + foreach ($texts as $text) { + $data .= \chr(\strlen($text)) . $text; + } + return $data; + } + + /** + * @param string $host + * @return string + */ + private function domainNameToBinary($host) + { + if ($host === '') { + return "\0"; + } + + // break up domain name at each dot that is not preceeded by a backslash (escaped notation) + return $this->textsToBinary( + \array_map( + 'stripcslashes', + \preg_split( + '/(?parse($data, 0); + if ($message === null) { + throw new InvalidArgumentException('Unable to parse binary message'); + } + + return $message; + } + + /** + * @param string $data + * @param int $consumed + * @return ?Message + */ + private function parse($data, $consumed) + { + if (!isset($data[12 - 1])) { + return null; + } + + list($id, $fields, $qdCount, $anCount, $nsCount, $arCount) = array_values(unpack('n*', substr($data, 0, 12))); + + $message = new Message(); + $message->id = $id; + $message->rcode = $fields & 0xf; + $message->ra = (($fields >> 7) & 1) === 1; + $message->rd = (($fields >> 8) & 1) === 1; + $message->tc = (($fields >> 9) & 1) === 1; + $message->aa = (($fields >> 10) & 1) === 1; + $message->opcode = ($fields >> 11) & 0xf; + $message->qr = (($fields >> 15) & 1) === 1; + $consumed += 12; + + // parse all questions + for ($i = $qdCount; $i > 0; --$i) { + list($question, $consumed) = $this->parseQuestion($data, $consumed); + if ($question === null) { + return null; + } else { + $message->questions[] = $question; + } + } + + // parse all answer records + for ($i = $anCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->answers[] = $record; + } + } + + // parse all authority records + for ($i = $nsCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->authority[] = $record; + } + } + + // parse all additional records + for ($i = $arCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->additional[] = $record; + } + } + + return $message; + } + + /** + * @param string $data + * @param int $consumed + * @return array + */ + private function parseQuestion($data, $consumed) + { + list($labels, $consumed) = $this->readLabels($data, $consumed); + + if ($labels === null || !isset($data[$consumed + 4 - 1])) { + return array(null, null); + } + + list($type, $class) = array_values(unpack('n*', substr($data, $consumed, 4))); + $consumed += 4; + + return array( + new Query( + implode('.', $labels), + $type, + $class + ), + $consumed + ); + } + + /** + * @param string $data + * @param int $consumed + * @return array An array with a parsed Record on success or array with null if data is invalid/incomplete + */ + private function parseRecord($data, $consumed) + { + list($name, $consumed) = $this->readDomain($data, $consumed); + + if ($name === null || !isset($data[$consumed + 10 - 1])) { + return array(null, null); + } + + list($type, $class) = array_values(unpack('n*', substr($data, $consumed, 4))); + $consumed += 4; + + list($ttl) = array_values(unpack('N', substr($data, $consumed, 4))); + $consumed += 4; + + // TTL is a UINT32 that must not have most significant bit set for BC reasons + if ($ttl < 0 || $ttl >= 1 << 31) { + $ttl = 0; + } + + list($rdLength) = array_values(unpack('n', substr($data, $consumed, 2))); + $consumed += 2; + + if (!isset($data[$consumed + $rdLength - 1])) { + return array(null, null); + } + + $rdata = null; + $expected = $consumed + $rdLength; + + if (Message::TYPE_A === $type) { + if ($rdLength === 4) { + $rdata = inet_ntop(substr($data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_AAAA === $type) { + if ($rdLength === 16) { + $rdata = inet_ntop(substr($data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_CNAME === $type || Message::TYPE_PTR === $type || Message::TYPE_NS === $type) { + list($rdata, $consumed) = $this->readDomain($data, $consumed); + } elseif (Message::TYPE_TXT === $type || Message::TYPE_SPF === $type) { + $rdata = array(); + while ($consumed < $expected) { + $len = ord($data[$consumed]); + $rdata[] = (string)substr($data, $consumed + 1, $len); + $consumed += $len + 1; + } + } elseif (Message::TYPE_MX === $type) { + if ($rdLength > 2) { + list($priority) = array_values(unpack('n', substr($data, $consumed, 2))); + list($target, $consumed) = $this->readDomain($data, $consumed + 2); + + $rdata = array( + 'priority' => $priority, + 'target' => $target + ); + } + } elseif (Message::TYPE_SRV === $type) { + if ($rdLength > 6) { + list($priority, $weight, $port) = array_values(unpack('n*', substr($data, $consumed, 6))); + list($target, $consumed) = $this->readDomain($data, $consumed + 6); + + $rdata = array( + 'priority' => $priority, + 'weight' => $weight, + 'port' => $port, + 'target' => $target + ); + } + } elseif (Message::TYPE_SSHFP === $type) { + if ($rdLength > 2) { + list($algorithm, $hash) = \array_values(\unpack('C*', \substr($data, $consumed, 2))); + $fingerprint = \bin2hex(\substr($data, $consumed + 2, $rdLength - 2)); + $consumed += $rdLength; + + $rdata = array( + 'algorithm' => $algorithm, + 'type' => $hash, + 'fingerprint' => $fingerprint + ); + } + } elseif (Message::TYPE_SOA === $type) { + list($mname, $consumed) = $this->readDomain($data, $consumed); + list($rname, $consumed) = $this->readDomain($data, $consumed); + + if ($mname !== null && $rname !== null && isset($data[$consumed + 20 - 1])) { + list($serial, $refresh, $retry, $expire, $minimum) = array_values(unpack('N*', substr($data, $consumed, 20))); + $consumed += 20; + + $rdata = array( + 'mname' => $mname, + 'rname' => $rname, + 'serial' => $serial, + 'refresh' => $refresh, + 'retry' => $retry, + 'expire' => $expire, + 'minimum' => $minimum + ); + } + } elseif (Message::TYPE_OPT === $type) { + $rdata = array(); + while (isset($data[$consumed + 4 - 1])) { + list($code, $length) = array_values(unpack('n*', substr($data, $consumed, 4))); + $value = (string) substr($data, $consumed + 4, $length); + if ($code === Message::OPT_TCP_KEEPALIVE && $value === '') { + $value = null; + } elseif ($code === Message::OPT_TCP_KEEPALIVE && $length === 2) { + list($value) = array_values(unpack('n', $value)); + $value = round($value * 0.1, 1); + } elseif ($code === Message::OPT_TCP_KEEPALIVE) { + break; + } + $rdata[$code] = $value; + $consumed += 4 + $length; + } + } elseif (Message::TYPE_CAA === $type) { + if ($rdLength > 3) { + list($flag, $tagLength) = array_values(unpack('C*', substr($data, $consumed, 2))); + + if ($tagLength > 0 && $rdLength - 2 - $tagLength > 0) { + $tag = substr($data, $consumed + 2, $tagLength); + $value = substr($data, $consumed + 2 + $tagLength, $rdLength - 2 - $tagLength); + $consumed += $rdLength; + + $rdata = array( + 'flag' => $flag, + 'tag' => $tag, + 'value' => $value + ); + } + } + } else { + // unknown types simply parse rdata as an opaque binary string + $rdata = substr($data, $consumed, $rdLength); + $consumed += $rdLength; + } + + // ensure parsing record data consumes expact number of bytes indicated in record length + if ($consumed !== $expected || $rdata === null) { + return array(null, null); + } + + return array( + new Record($name, $type, $class, $ttl, $rdata), + $consumed + ); + } + + private function readDomain($data, $consumed) + { + list ($labels, $consumed) = $this->readLabels($data, $consumed); + + if ($labels === null) { + return array(null, null); + } + + // use escaped notation for each label part, then join using dots + return array( + \implode( + '.', + \array_map( + function ($label) { + return \addcslashes($label, "\0..\40.\177"); + }, + $labels + ) + ), + $consumed + ); + } + + /** + * @param string $data + * @param int $consumed + * @param int $compressionDepth maximum depth for compressed labels to avoid unreasonable recursion + * @return array + */ + private function readLabels($data, $consumed, $compressionDepth = 127) + { + $labels = array(); + + while (true) { + if (!isset($data[$consumed])) { + return array(null, null); + } + + $length = \ord($data[$consumed]); + + // end of labels reached + if ($length === 0) { + $consumed += 1; + break; + } + + // first two bits set? this is a compressed label (14 bit pointer offset) + if (($length & 0xc0) === 0xc0 && isset($data[$consumed + 1]) && $compressionDepth) { + $offset = ($length & ~0xc0) << 8 | \ord($data[$consumed + 1]); + if ($offset >= $consumed) { + return array(null, null); + } + + $consumed += 2; + list($newLabels) = $this->readLabels($data, $offset, $compressionDepth - 1); + + if ($newLabels === null) { + return array(null, null); + } + + $labels = array_merge($labels, $newLabels); + break; + } + + // length MUST be 0-63 (6 bits only) and data has to be large enough + if ($length & 0xc0 || !isset($data[$consumed + $length - 1])) { + return array(null, null); + } + + $labels[] = substr($data, $consumed + 1, $length); + $consumed += $length + 1; + } + + return array($labels, $consumed); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/CachingExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/CachingExecutor.php new file mode 100644 index 0000000..e530b24 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/CachingExecutor.php @@ -0,0 +1,88 @@ +executor = $executor; + $this->cache = $cache; + } + + public function query(Query $query) + { + $id = $query->name . ':' . $query->type . ':' . $query->class; + $cache = $this->cache; + $that = $this; + $executor = $this->executor; + + $pending = $cache->get($id); + return new Promise(function ($resolve, $reject) use ($query, $id, $cache, $executor, &$pending, $that) { + $pending->then( + function ($message) use ($query, $id, $cache, $executor, &$pending, $that) { + // return cached response message on cache hit + if ($message !== null) { + return $message; + } + + // perform DNS lookup if not already cached + return $pending = $executor->query($query)->then( + function (Message $message) use ($cache, $id, $that) { + // DNS response message received => store in cache when not truncated and return + if (!$message->tc) { + $cache->set($id, $message, $that->ttl($message)); + } + + return $message; + } + ); + } + )->then($resolve, function ($e) use ($reject, &$pending) { + $reject($e); + $pending = null; + }); + }, function ($_, $reject) use (&$pending, $query) { + $reject(new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled')); + $pending->cancel(); + $pending = null; + }); + } + + /** + * @param Message $message + * @return int + * @internal + */ + public function ttl(Message $message) + { + // select TTL from answers (should all be the same), use smallest value if available + // @link https://tools.ietf.org/html/rfc2181#section-5.2 + $ttl = null; + foreach ($message->answers as $answer) { + if ($ttl === null || $answer->ttl < $ttl) { + $ttl = $answer->ttl; + } + } + + if ($ttl === null) { + $ttl = self::TTL; + } + + return $ttl; + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/CancellationException.php b/trilhas_poo/vendor/react/dns/src/Query/CancellationException.php new file mode 100644 index 0000000..5432b36 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/CancellationException.php @@ -0,0 +1,7 @@ +executor = $base; + } + + public function query(Query $query) + { + $key = $this->serializeQueryToIdentity($query); + if (isset($this->pending[$key])) { + // same query is already pending, so use shared reference to pending query + $promise = $this->pending[$key]; + ++$this->counts[$key]; + } else { + // no such query pending, so start new query and keep reference until it's fulfilled or rejected + $promise = $this->executor->query($query); + $this->pending[$key] = $promise; + $this->counts[$key] = 1; + + $pending =& $this->pending; + $counts =& $this->counts; + $promise->then(function () use ($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }, function () use ($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }); + } + + // Return a child promise awaiting the pending query. + // Cancelling this child promise should only cancel the pending query + // when no other child promise is awaiting the same query. + $pending =& $this->pending; + $counts =& $this->counts; + return new Promise(function ($resolve, $reject) use ($promise) { + $promise->then($resolve, $reject); + }, function () use (&$promise, $key, $query, &$pending, &$counts) { + if (--$counts[$key] < 1) { + unset($pending[$key], $counts[$key]); + $promise->cancel(); + $promise = null; + } + throw new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + } + + private function serializeQueryToIdentity(Query $query) + { + return sprintf('%s:%s:%s', $query->name, $query->type, $query->class); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/ExecutorInterface.php b/trilhas_poo/vendor/react/dns/src/Query/ExecutorInterface.php new file mode 100644 index 0000000..0bc3945 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/ExecutorInterface.php @@ -0,0 +1,43 @@ +query($query)->then( + * function (React\Dns\Model\Message $response) { + * // response message successfully received + * var_dump($response->rcode, $response->answers); + * }, + * function (Exception $error) { + * // failed to query due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $executor->query($query); + * + * $promise->cancel(); + * ``` + * + * @param Query $query + * @return \React\Promise\PromiseInterface<\React\Dns\Model\Message> + * resolves with response message on success or rejects with an Exception on error + */ + public function query(Query $query); +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/FallbackExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/FallbackExecutor.php new file mode 100644 index 0000000..83bd360 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/FallbackExecutor.php @@ -0,0 +1,49 @@ +executor = $executor; + $this->fallback = $fallback; + } + + public function query(Query $query) + { + $cancelled = false; + $fallback = $this->fallback; + $promise = $this->executor->query($query); + + return new Promise(function ($resolve, $reject) use (&$promise, $fallback, $query, &$cancelled) { + $promise->then($resolve, function (\Exception $e1) use ($fallback, $query, $resolve, $reject, &$cancelled, &$promise) { + // reject if primary resolution rejected due to cancellation + if ($cancelled) { + $reject($e1); + return; + } + + // start fallback query if primary query rejected + $promise = $fallback->query($query)->then($resolve, function (\Exception $e2) use ($e1, $reject) { + $append = $e2->getMessage(); + if (($pos = strpos($append, ':')) !== false) { + $append = substr($append, $pos + 2); + } + + // reject with combined error message if both queries fail + $reject(new \RuntimeException($e1->getMessage() . '. ' . $append)); + }); + }); + }, function () use (&$promise, &$cancelled) { + // cancel pending query (primary or fallback) + $cancelled = true; + $promise->cancel(); + }); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/HostsFileExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/HostsFileExecutor.php new file mode 100644 index 0000000..d6e2d93 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/HostsFileExecutor.php @@ -0,0 +1,89 @@ +hosts = $hosts; + $this->fallback = $fallback; + } + + public function query(Query $query) + { + if ($query->class === Message::CLASS_IN && ($query->type === Message::TYPE_A || $query->type === Message::TYPE_AAAA)) { + // forward lookup for type A or AAAA + $records = array(); + $expectsColon = $query->type === Message::TYPE_AAAA; + foreach ($this->hosts->getIpsForHost($query->name) as $ip) { + // ensure this is an IPv4/IPV6 address according to query type + if ((strpos($ip, ':') !== false) === $expectsColon) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $ip); + } + } + + if ($records) { + return Promise\resolve( + Message::createResponseWithAnswersForQuery($query, $records) + ); + } + } elseif ($query->class === Message::CLASS_IN && $query->type === Message::TYPE_PTR) { + // reverse lookup: extract IPv4 or IPv6 from special `.arpa` domain + $ip = $this->getIpFromHost($query->name); + + if ($ip !== null) { + $records = array(); + foreach ($this->hosts->getHostsForIp($ip) as $host) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $host); + } + + if ($records) { + return Promise\resolve( + Message::createResponseWithAnswersForQuery($query, $records) + ); + } + } + } + + return $this->fallback->query($query); + } + + private function getIpFromHost($host) + { + if (substr($host, -13) === '.in-addr.arpa') { + // IPv4: read as IP and reverse bytes + $ip = @inet_pton(substr($host, 0, -13)); + if ($ip === false || isset($ip[4])) { + return null; + } + + return inet_ntop(strrev($ip)); + } elseif (substr($host, -9) === '.ip6.arpa') { + // IPv6: replace dots, reverse nibbles and interpret as hexadecimal string + $ip = @inet_ntop(pack('H*', strrev(str_replace('.', '', substr($host, 0, -9))))); + if ($ip === false) { + return null; + } + + return $ip; + } else { + return null; + } + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/Query.php b/trilhas_poo/vendor/react/dns/src/Query/Query.php new file mode 100644 index 0000000..a3dcfb5 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/Query.php @@ -0,0 +1,69 @@ +name = $name; + $this->type = $type; + $this->class = $class; + } + + /** + * Describes the hostname and query type/class for this query + * + * The output format is supposed to be human readable and is subject to change. + * The format is inspired by RFC 3597 when handling unkown types/classes. + * + * @return string "example.com (A)" or "example.com (CLASS0 TYPE1234)" + * @link https://tools.ietf.org/html/rfc3597 + */ + public function describe() + { + $class = $this->class !== Message::CLASS_IN ? 'CLASS' . $this->class . ' ' : ''; + + $type = 'TYPE' . $this->type; + $ref = new \ReflectionClass('React\Dns\Model\Message'); + foreach ($ref->getConstants() as $name => $value) { + if ($value === $this->type && \strpos($name, 'TYPE_') === 0) { + $type = \substr($name, 5); + break; + } + } + + return $this->name . ' (' . $class . $type . ')'; + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/RetryExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/RetryExecutor.php new file mode 100644 index 0000000..11c123b --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/RetryExecutor.php @@ -0,0 +1,87 @@ +executor = $executor; + $this->retries = $retries; + } + + public function query(Query $query) + { + return $this->tryQuery($query, $this->retries); + } + + public function tryQuery(Query $query, $retries) + { + $deferred = new Deferred(function () use (&$promise) { + if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) { + $promise->cancel(); + } + }); + + $success = function ($value) use ($deferred, &$errorback) { + $errorback = null; + $deferred->resolve($value); + }; + + $executor = $this->executor; + $errorback = function ($e) use ($deferred, &$promise, $query, $success, &$errorback, &$retries, $executor) { + if (!$e instanceof TimeoutException) { + $errorback = null; + $deferred->reject($e); + } elseif ($retries <= 0) { + $errorback = null; + $deferred->reject($e = new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: too many retries', + 0, + $e + )); + + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + if (\PHP_VERSION_ID < 80100) { + $r->setAccessible(true); + } + $trace = $r->getValue($e); + + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } else { + --$retries; + $promise = $executor->query($query)->then( + $success, + $errorback + ); + } + }; + + $promise = $this->executor->query($query)->then( + $success, + $errorback + ); + + return $deferred->promise(); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/SelectiveTransportExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/SelectiveTransportExecutor.php new file mode 100644 index 0000000..0f0ca5d --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/SelectiveTransportExecutor.php @@ -0,0 +1,85 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * Note that this executor only implements the logic to select the correct + * transport for the given DNS query. Implementing the correct transport logic, + * implementing timeouts and any retry logic is left up to the given executors, + * see also [`UdpTransportExecutor`](#udptransportexecutor) and + * [`TcpTransportExecutor`](#tcptransportexecutor) for more details. + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new SelectiveTransportExecutor( + * $datagramExecutor, + * $streamExecutor + * ) + * ); + * ``` + */ +class SelectiveTransportExecutor implements ExecutorInterface +{ + private $datagramExecutor; + private $streamExecutor; + + public function __construct(ExecutorInterface $datagramExecutor, ExecutorInterface $streamExecutor) + { + $this->datagramExecutor = $datagramExecutor; + $this->streamExecutor = $streamExecutor; + } + + public function query(Query $query) + { + $stream = $this->streamExecutor; + $pending = $this->datagramExecutor->query($query); + + return new Promise(function ($resolve, $reject) use (&$pending, $stream, $query) { + $pending->then( + $resolve, + function ($e) use (&$pending, $stream, $query, $resolve, $reject) { + if ($e->getCode() === (\defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90)) { + $pending = $stream->query($query)->then($resolve, $reject); + } else { + $reject($e); + } + } + ); + }, function () use (&$pending) { + $pending->cancel(); + $pending = null; + }); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/TcpTransportExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/TcpTransportExecutor.php new file mode 100644 index 0000000..669fd01 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/TcpTransportExecutor.php @@ -0,0 +1,382 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also [example #92](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP + * transport, so you do not necessarily have to implement any retry logic. + * + * Note that this executor is entirely async and as such allows you to execute + * queries concurrently. The first query will establish a TCP/IP socket + * connection to the DNS server which will be kept open for a short period. + * Additional queries will automatically reuse this existing socket connection + * to the DNS server, will pipeline multiple requests over this single + * connection and will keep an idle connection open for a short period. The + * initial TCP/IP connection overhead may incur a slight delay if you only send + * occasional queries – when sending a larger number of concurrent queries over + * an existing connection, it becomes increasingly more efficient and avoids + * creating many concurrent sockets like the UDP-based executor. You may still + * want to limit the number of (concurrent) queries in your application or you + * may be facing rate limitations and bans on the resolver end. For many common + * applications, you may want to avoid sending the same query multiple times + * when the first one is still pending, so you will likely want to use this in + * combination with a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's TCP/IP sockets and does not take advantage + * of [react/socket](https://github.com/reactphp/socket) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Socket + * component instead of reimplementing this socket logic from scratch. + */ +class TcpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + + /** + * @var ?resource + */ + private $socket; + + /** + * @var Deferred[] + */ + private $pending = array(); + + /** + * @var string[] + */ + private $names = array(); + + /** + * Maximum idle time when socket is current unused (i.e. no pending queries outstanding) + * + * If a new query is to be sent during the idle period, we can reuse the + * existing socket without having to wait for a new socket connection. + * This uses a rather small, hard-coded value to not keep any unneeded + * sockets open and to not keep the loop busy longer than needed. + * + * A future implementation may take advantage of `edns-tcp-keepalive` to keep + * the socket open for longer periods. This will likely require explicit + * configuration because this may consume additional resources and also keep + * the loop busy for longer than expected in some applications. + * + * @var float + * @link https://tools.ietf.org/html/rfc7766#section-6.2.1 + * @link https://tools.ietf.org/html/rfc7828 + */ + private $idlePeriod = 0.001; + + /** + * @var ?\React\EventLoop\TimerInterface + */ + private $idleTimer; + + private $writeBuffer = ''; + private $writePending = false; + + private $readBuffer = ''; + private $readPending = false; + + /** @var string */ + private $readChunk = 0xffff; + + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, $loop = null) + { + if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + + $parts = \parse_url((\strpos($nameserver, '://') === false ? 'tcp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'tcp' || @\inet_pton(\trim($parts['host'], '[]')) === false) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + $this->nameserver = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + + // keep shuffing message ID to avoid using the same message ID for two pending queries at the same time + while (isset($this->pending[$request->id])) { + $request->id = \mt_rand(0, 0xffff); // @codeCoverageIgnore + } + + $queryData = $this->dumper->toBinary($request); + $length = \strlen($queryData); + if ($length > 0xffff) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Query too large for TCP transport' + )); + } + + $queryData = \pack('n', $length) . $queryData; + + if ($this->socket === null) { + // create async TCP/IP connection (may take a while) + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT); + if ($socket === false) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + )); + } + + // set socket to non-blocking and wait for it to become writable (connection success/rejected) + \stream_set_blocking($socket, false); + if (\function_exists('stream_set_chunk_size')) { + \stream_set_chunk_size($socket, $this->readChunk); // @codeCoverageIgnore + } + $this->socket = $socket; + } + + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + + // wait for socket to become writable to actually write out data + $this->writeBuffer .= $queryData; + if (!$this->writePending) { + $this->writePending = true; + $this->loop->addWriteStream($this->socket, array($this, 'handleWritable')); + } + + $names =& $this->names; + $that = $this; + $deferred = new Deferred(function () use ($that, &$names, $request) { + // remove from list of pending names, but remember pending query + $name = $names[$request->id]; + unset($names[$request->id]); + $that->checkIdle(); + + throw new CancellationException('DNS query for ' . $name . ' has been cancelled'); + }); + + $this->pending[$request->id] = $deferred; + $this->names[$request->id] = $query->describe(); + + return $deferred->promise(); + } + + /** + * @internal + */ + public function handleWritable() + { + if ($this->readPending === false) { + $name = @\stream_socket_get_name($this->socket, true); + if ($name === false) { + // Connection failed? Check socket error if available for underlying errno/errstr. + // @codeCoverageIgnoreStart + if (\function_exists('socket_import_stream')) { + $socket = \socket_import_stream($this->socket); + $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR); + $errstr = \socket_strerror($errno); + } else { + $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111; + $errstr = 'Connection refused'; + } + // @codeCoverageIgnoreEnd + + $this->closeError('Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno); + return; + } + + $this->readPending = true; + $this->loop->addReadStream($this->socket, array($this, 'handleRead')); + } + + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fwrite(): Send of 327712 bytes failed with errno=32 Broken pipe + \preg_match('/errno=(\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + + $written = \fwrite($this->socket, $this->writeBuffer); + + \restore_error_handler(); + + if ($written === false || $written === 0) { + $this->closeError( + 'Unable to send query to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + ); + return; + } + + if (isset($this->writeBuffer[$written])) { + $this->writeBuffer = \substr($this->writeBuffer, $written); + } else { + $this->loop->removeWriteStream($this->socket); + $this->writePending = false; + $this->writeBuffer = ''; + } + } + + /** + * @internal + */ + public function handleRead() + { + // read one chunk of data from the DNS server + // any error is fatal, this is a stream of TCP/IP data + $chunk = @\fread($this->socket, $this->readChunk); + if ($chunk === false || $chunk === '') { + $this->closeError('Connection to DNS server ' . $this->nameserver . ' lost'); + return; + } + + // reassemble complete message by concatenating all chunks. + $this->readBuffer .= $chunk; + + // response message header contains at least 12 bytes + while (isset($this->readBuffer[11])) { + // read response message length from first 2 bytes and ensure we have length + data in buffer + list(, $length) = \unpack('n', $this->readBuffer); + if (!isset($this->readBuffer[$length + 1])) { + return; + } + + $data = \substr($this->readBuffer, 2, $length); + $this->readBuffer = (string)substr($this->readBuffer, $length + 2); + + try { + $response = $this->parser->parseMessage($data); + } catch (\Exception $e) { + // reject all pending queries if we received an invalid message from remote server + $this->closeError('Invalid message received from DNS server ' . $this->nameserver); + return; + } + + // reject all pending queries if we received an unexpected response ID or truncated response + if (!isset($this->pending[$response->id]) || $response->tc) { + $this->closeError('Invalid response message received from DNS server ' . $this->nameserver); + return; + } + + $deferred = $this->pending[$response->id]; + unset($this->pending[$response->id], $this->names[$response->id]); + + $deferred->resolve($response); + + $this->checkIdle(); + } + } + + /** + * @internal + * @param string $reason + * @param int $code + */ + public function closeError($reason, $code = 0) + { + $this->readBuffer = ''; + if ($this->readPending) { + $this->loop->removeReadStream($this->socket); + $this->readPending = false; + } + + $this->writeBuffer = ''; + if ($this->writePending) { + $this->loop->removeWriteStream($this->socket); + $this->writePending = false; + } + + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + + @\fclose($this->socket); + $this->socket = null; + + foreach ($this->names as $id => $name) { + $this->pending[$id]->reject(new \RuntimeException( + 'DNS query for ' . $name . ' failed: ' . $reason, + $code + )); + } + $this->pending = $this->names = array(); + } + + /** + * @internal + */ + public function checkIdle() + { + if ($this->idleTimer === null && !$this->names) { + $that = $this; + $this->idleTimer = $this->loop->addTimer($this->idlePeriod, function () use ($that) { + $that->closeError('Idle timeout'); + }); + } + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/TimeoutException.php b/trilhas_poo/vendor/react/dns/src/Query/TimeoutException.php new file mode 100644 index 0000000..109b0a9 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/TimeoutException.php @@ -0,0 +1,7 @@ +executor = $executor; + $this->loop = $loop ?: Loop::get(); + $this->timeout = $timeout; + } + + public function query(Query $query) + { + $promise = $this->executor->query($query); + + $loop = $this->loop; + $time = $this->timeout; + return new Promise(function ($resolve, $reject) use ($loop, $time, $promise, $query) { + $timer = null; + $promise = $promise->then(function ($v) use (&$timer, $loop, $resolve) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $resolve($v); + }, function ($v) use (&$timer, $loop, $reject) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $reject($v); + }); + + // promise already resolved => no need to start timer + if ($timer === false) { + return; + } + + // start timeout timer which will cancel the pending promise + $timer = $loop->addTimer($time, function () use ($time, &$promise, $reject, $query) { + $reject(new TimeoutException( + 'DNS query for ' . $query->describe() . ' timed out' + )); + + // Cancel pending query to clean up any underlying resources and references. + // Avoid garbage references in call stack by passing pending promise by reference. + assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + }, function () use (&$promise) { + // Cancelling this promise will cancel the pending query, thus triggering the rejection logic above. + // Avoid garbage references in call stack by passing pending promise by reference. + assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Query/UdpTransportExecutor.php b/trilhas_poo/vendor/react/dns/src/Query/UdpTransportExecutor.php new file mode 100644 index 0000000..a8cbfaf --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Query/UdpTransportExecutor.php @@ -0,0 +1,221 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also the [fourth example](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Also note that this executor uses an unreliable UDP transport and that it + * does not implement any retry logic, so you will likely want to use this in + * combination with a `RetryExecutor` like this: + * + * ```php + * $executor = new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's UDP sockets and does not take advantage + * of [react/datagram](https://github.com/reactphp/datagram) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Datagram + * component instead of reimplementing this socket logic from scratch. + */ +final class UdpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + + /** + * maximum UDP packet size to send and receive + * + * @var int + */ + private $maxPacketSize = 512; + + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, $loop = null) + { + if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + + $parts = \parse_url((\strpos($nameserver, '://') === false ? 'udp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'udp' || @\inet_pton(\trim($parts['host'], '[]')) === false) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + $this->nameserver = 'udp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + + $queryData = $this->dumper->toBinary($request); + if (isset($queryData[$this->maxPacketSize])) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Query too large for UDP transport', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 + )); + } + + // UDP connections are instant, so try connection without a loop or timeout + $errno = 0; + $errstr = ''; + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0); + if ($socket === false) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + )); + } + + // set socket to non-blocking and immediately try to send (fill write buffer) + \stream_set_blocking($socket, false); + + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // Write may potentially fail, but most common errors are already caught by connection check above. + // Among others, macOS is known to report here when trying to send to broadcast address. + // This can also be reproduced by writing data exceeding `stream_set_chunk_size()` to a server refusing UDP data. + // fwrite(): send of 8192 bytes failed with errno=111 Connection refused + \preg_match('/errno=(\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + + $written = \fwrite($socket, $queryData); + + \restore_error_handler(); + + if ($written !== \strlen($queryData)) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to send query to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + )); + } + + $loop = $this->loop; + $deferred = new Deferred(function () use ($loop, $socket, $query) { + // cancellation should remove socket from loop and close socket + $loop->removeReadStream($socket); + \fclose($socket); + + throw new CancellationException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + + $max = $this->maxPacketSize; + $parser = $this->parser; + $nameserver = $this->nameserver; + $loop->addReadStream($socket, function ($socket) use ($loop, $deferred, $query, $parser, $request, $max, $nameserver) { + // try to read a single data packet from the DNS server + // ignoring any errors, this is uses UDP packets and not a stream of data + $data = @\fread($socket, $max); + if ($data === false) { + return; + } + + try { + $response = $parser->parseMessage($data); + } catch (\Exception $e) { + // ignore and await next if we received an invalid message from remote server + // this may as well be a fake response from an attacker (possible DOS) + return; + } + + // ignore and await next if we received an unexpected response ID + // this may as well be a fake response from an attacker (possible cache poisoning) + if ($response->id !== $request->id) { + return; + } + + // we only react to the first valid message, so remove socket from loop and close + $loop->removeReadStream($socket); + \fclose($socket); + + if ($response->tc) { + $deferred->reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: The DNS server ' . $nameserver . ' returned a truncated result for a UDP query', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 + )); + return; + } + + $deferred->resolve($response); + }); + + return $deferred->promise(); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/RecordNotFoundException.php b/trilhas_poo/vendor/react/dns/src/RecordNotFoundException.php new file mode 100644 index 0000000..3b70274 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/RecordNotFoundException.php @@ -0,0 +1,7 @@ +decorateHostsFileExecutor($this->createExecutor($config, $loop ?: Loop::get())); + + return new Resolver($executor); + } + + /** + * Creates a cached DNS resolver instance for the given DNS config and cache + * + * As of v1.7.0 it's recommended to pass a `Config` object instead of a + * single nameserver address. If the given config contains more than one DNS + * nameserver, all DNS nameservers will be used in order. The primary DNS + * server will always be used first before falling back to the secondary or + * tertiary DNS server. + * + * @param Config|string $config DNS Config object (recommended) or single nameserver address + * @param ?LoopInterface $loop + * @param ?CacheInterface $cache + * @return \React\Dns\Resolver\ResolverInterface + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + public function createCached($config, $loop = null, $cache = null) + { + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + if ($cache !== null && !$cache instanceof CacheInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #3 ($cache) expected null|React\Cache\CacheInterface'); + } + + // default to keeping maximum of 256 responses in cache unless explicitly given + if (!($cache instanceof CacheInterface)) { + $cache = new ArrayCache(256); + } + + $executor = $this->createExecutor($config, $loop ?: Loop::get()); + $executor = new CachingExecutor($executor, $cache); + $executor = $this->decorateHostsFileExecutor($executor); + + return new Resolver($executor); + } + + /** + * Tries to load the hosts file and decorates the given executor on success + * + * @param ExecutorInterface $executor + * @return ExecutorInterface + * @codeCoverageIgnore + */ + private function decorateHostsFileExecutor(ExecutorInterface $executor) + { + try { + $executor = new HostsFileExecutor( + HostsFile::loadFromPathBlocking(), + $executor + ); + } catch (\RuntimeException $e) { + // ignore this file if it can not be loaded + } + + // Windows does not store localhost in hosts file by default but handles this internally + // To compensate for this, we explicitly use hard-coded defaults for localhost + if (DIRECTORY_SEPARATOR === '\\') { + $executor = new HostsFileExecutor( + new HostsFile("127.0.0.1 localhost\n::1 localhost"), + $executor + ); + } + + return $executor; + } + + /** + * @param Config|string $nameserver + * @param LoopInterface $loop + * @return CoopExecutor + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + private function createExecutor($nameserver, LoopInterface $loop) + { + if ($nameserver instanceof Config) { + if (!$nameserver->nameservers) { + throw new \UnderflowException('Empty config with no DNS servers'); + } + + // Hard-coded to check up to 3 DNS servers to match default limits in place in most systems (see MAXNS config). + // Note to future self: Recursion isn't too hard, but how deep do we really want to go? + $primary = reset($nameserver->nameservers); + $secondary = next($nameserver->nameservers); + $tertiary = next($nameserver->nameservers); + + if ($tertiary !== false) { + // 3 DNS servers given => nest first with fallback for second and third + return new CoopExecutor( + new RetryExecutor( + new FallbackExecutor( + $this->createSingleExecutor($primary, $loop), + new FallbackExecutor( + $this->createSingleExecutor($secondary, $loop), + $this->createSingleExecutor($tertiary, $loop) + ) + ) + ) + ); + } elseif ($secondary !== false) { + // 2 DNS servers given => fallback from first to second + return new CoopExecutor( + new RetryExecutor( + new FallbackExecutor( + $this->createSingleExecutor($primary, $loop), + $this->createSingleExecutor($secondary, $loop) + ) + ) + ); + } else { + // 1 DNS server given => use single executor + $nameserver = $primary; + } + } + + return new CoopExecutor(new RetryExecutor($this->createSingleExecutor($nameserver, $loop))); + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return ExecutorInterface + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createSingleExecutor($nameserver, LoopInterface $loop) + { + $parts = \parse_url($nameserver); + + if (isset($parts['scheme']) && $parts['scheme'] === 'tcp') { + $executor = $this->createTcpExecutor($nameserver, $loop); + } elseif (isset($parts['scheme']) && $parts['scheme'] === 'udp') { + $executor = $this->createUdpExecutor($nameserver, $loop); + } else { + $executor = new SelectiveTransportExecutor( + $this->createUdpExecutor($nameserver, $loop), + $this->createTcpExecutor($nameserver, $loop) + ); + } + + return $executor; + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createTcpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor( + new TcpTransportExecutor($nameserver, $loop), + 5.0, + $loop + ); + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createUdpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor( + new UdpTransportExecutor( + $nameserver, + $loop + ), + 5.0, + $loop + ); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Resolver/Resolver.php b/trilhas_poo/vendor/react/dns/src/Resolver/Resolver.php new file mode 100644 index 0000000..92926f3 --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Resolver/Resolver.php @@ -0,0 +1,147 @@ +executor = $executor; + } + + public function resolve($domain) + { + return $this->resolveAll($domain, Message::TYPE_A)->then(function (array $ips) { + return $ips[array_rand($ips)]; + }); + } + + public function resolveAll($domain, $type) + { + $query = new Query($domain, $type, Message::CLASS_IN); + $that = $this; + + return $this->executor->query( + $query + )->then(function (Message $response) use ($query, $that) { + return $that->extractValues($query, $response); + }); + } + + /** + * [Internal] extract all resource record values from response for this query + * + * @param Query $query + * @param Message $response + * @return array + * @throws RecordNotFoundException when response indicates an error or contains no data + * @internal + */ + public function extractValues(Query $query, Message $response) + { + // reject if response code indicates this is an error response message + $code = $response->rcode; + if ($code !== Message::RCODE_OK) { + switch ($code) { + case Message::RCODE_FORMAT_ERROR: + $message = 'Format Error'; + break; + case Message::RCODE_SERVER_FAILURE: + $message = 'Server Failure'; + break; + case Message::RCODE_NAME_ERROR: + $message = 'Non-Existent Domain / NXDOMAIN'; + break; + case Message::RCODE_NOT_IMPLEMENTED: + $message = 'Not Implemented'; + break; + case Message::RCODE_REFUSED: + $message = 'Refused'; + break; + default: + $message = 'Unknown error response code ' . $code; + } + throw new RecordNotFoundException( + 'DNS query for ' . $query->describe() . ' returned an error response (' . $message . ')', + $code + ); + } + + $answers = $response->answers; + $addresses = $this->valuesByNameAndType($answers, $query->name, $query->type); + + // reject if we did not receive a valid answer (domain is valid, but no record for this type could be found) + if (0 === count($addresses)) { + throw new RecordNotFoundException( + 'DNS query for ' . $query->describe() . ' did not return a valid answer (NOERROR / NODATA)' + ); + } + + return array_values($addresses); + } + + /** + * @param \React\Dns\Model\Record[] $answers + * @param string $name + * @param int $type + * @return array + */ + private function valuesByNameAndType(array $answers, $name, $type) + { + // return all record values for this name and type (if any) + $named = $this->filterByName($answers, $name); + $records = $this->filterByType($named, $type); + if ($records) { + return $this->mapRecordData($records); + } + + // no matching records found? check if there are any matching CNAMEs instead + $cnameRecords = $this->filterByType($named, Message::TYPE_CNAME); + if ($cnameRecords) { + $cnames = $this->mapRecordData($cnameRecords); + foreach ($cnames as $cname) { + $records = array_merge( + $records, + $this->valuesByNameAndType($answers, $cname, $type) + ); + } + } + + return $records; + } + + private function filterByName(array $answers, $name) + { + return $this->filterByField($answers, 'name', $name); + } + + private function filterByType(array $answers, $type) + { + return $this->filterByField($answers, 'type', $type); + } + + private function filterByField(array $answers, $field, $value) + { + $value = strtolower($value); + return array_filter($answers, function ($answer) use ($field, $value) { + return $value === strtolower($answer->$field); + }); + } + + private function mapRecordData(array $records) + { + return array_map(function ($record) { + return $record->data; + }, $records); + } +} diff --git a/trilhas_poo/vendor/react/dns/src/Resolver/ResolverInterface.php b/trilhas_poo/vendor/react/dns/src/Resolver/ResolverInterface.php new file mode 100644 index 0000000..555a1cb --- /dev/null +++ b/trilhas_poo/vendor/react/dns/src/Resolver/ResolverInterface.php @@ -0,0 +1,94 @@ +resolve('reactphp.org')->then(function ($ip) { + * echo 'IP for reactphp.org is ' . $ip . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a single IP + * address on success. + * + * If the DNS server sends a DNS response message that contains more than + * one IP address for this query, it will randomly pick one of the IP + * addresses from the response. If you want the full list of IP addresses + * or want to send a different type of query, you should use the + * [`resolveAll()`](#resolveall) method instead. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolve('reactphp.org'); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * resolves with a single IP address on success or rejects with an Exception on error. + */ + public function resolve($domain); + + /** + * Resolves all record values for the given $domain name and query $type. + * + * ```php + * $resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + * echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * + * $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + * echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a list with all + * record values on success. + * + * If the DNS server sends a DNS response message that contains one or more + * records for this query, it will return a list with all record values + * from the response. You can use the `Message::TYPE_*` constants to control + * which type of query will be sent. Note that this method always returns a + * list of record values, but each record value type depends on the query + * type. For example, it returns the IPv4 addresses for type `A` queries, + * the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, + * `CNAME` and `PTR` queries and structured data for other queries. See also + * the `Record` documentation for more details. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * Resolves with all record values on success or rejects with an Exception on error. + */ + public function resolveAll($domain, $type); +} diff --git a/trilhas_poo/vendor/react/event-loop/CHANGELOG.md b/trilhas_poo/vendor/react/event-loop/CHANGELOG.md new file mode 100644 index 0000000..7d41909 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/CHANGELOG.md @@ -0,0 +1,473 @@ +# Changelog + +## 1.6.0 (2025-11-17) + +* Feature: Improve PHP 8.5+ support by avoiding deprecated method calls. + (#280 and #282 by @WyriHaximus) + +## 1.5.0 (2023-11-13) + +* Feature: Improve performance by using `spl_object_id()` on PHP 7.2+. + (#267 by @samsonasik) + +* Feature: Full PHP 8.3 compatibility. + (#269 by @clue) + +* Update tests for `ext-uv` on PHP 8+ and legacy PHP. + (#270 by @clue and #268 by @SimonFrings) + +## 1.4.0 (2023-05-05) + +* Feature: Improve performance of `Loop` by avoiding unneeded method calls. + (#266 by @clue) + +* Feature: Support checking `EINTR` constant from `ext-pcntl` without `ext-sockets`. + (#265 by @clue) + +* Minor documentation improvements. + (#254 by @nhedger) + +* Improve test suite, run tests on PHP 8.2 and report failed assertions. + (#258 by @WyriHaximus, #264 by @clue and #251, #261 and #262 by @SimonFrings) + +## 1.3.0 (2022-03-17) + +* Feature: Improve default `StreamSelectLoop` to report any warnings for invalid streams. + (#245 by @clue) + +* Feature: Improve performance of `StreamSelectLoop` when no timers are scheduled. + (#246 by @clue) + +* Fix: Fix periodic timer with zero interval for `ExtEvLoop` and legacy `ExtLibevLoop`. + (#243 by @lucasnetau) + +* Minor documentation improvements, update PHP version references. + (#240, #248 and #250 by @SimonFrings, #241 by @dbu and #249 by @clue) + +* Improve test suite and test against PHP 8.1. + (#238 by @WyriHaximus and #242 by @clue) + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Introduce new concept of default loop with the new `Loop` class. + (#226 by @WyriHaximus, #229, #231 and #232 by @clue) + + The `Loop` class exists as a convenient global accessor for the event loop. + It provides all methods that exist on the `LoopInterface` as static methods and + will automatically execute the loop at the end of the program: + + ```php + $timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; + }); + + Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; + }); + ``` + + The explicit loop instructions are still valid and may still be useful in some applications, + especially for a transition period towards the more concise style. + The `Loop::get()` method can be used to get the currently active event loop instance. + + ```php + // deprecated + $loop = React\EventLoop\Factory::create(); + + // new + $loop = React\EventLoop\Loop::get(); + ``` + +* Minor documentation improvements and mark legacy extensions as deprecated. + (#234 by @SimonFrings, #214 by @WyriHaximus and #233 and #235 by @nhedger) + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config and run tests on PHP 8. + (#212 and #215 by @SimonFrings and #230 by @clue) + +## 1.1.1 (2020-01-01) + +* Fix: Fix reporting connection refused errors with `ExtUvLoop` on Linux and `StreamSelectLoop` on Windows. + (#207 and #208 by @clue) + +* Fix: Fix unsupported EventConfig and `SEGFAULT` on shutdown with `ExtEventLoop` on Windows. + (#205 by @clue) + +* Fix: Prevent interval overflow for timers very far in the future with `ExtUvLoop`. + (#196 by @PabloKowalczyk) + +* Fix: Check PCNTL functions for signal support instead of PCNTL extension with `StreamSelectLoop`. + (#195 by @clue) + +* Add `.gitattributes` to exclude dev files from exports. + (#201 by @reedy) + +* Improve test suite to fix testing `ExtUvLoop` on Travis, + fix Travis CI builds, do not install `libuv` on legacy PHP setups, + fix failing test cases due to inaccurate timers, + run tests on Windows via Travis CI and + run tests on PHP 7.4 and simplify test matrix and test setup. + (#197 by @WyriHaximus and #202, #203, #204 and #209 by @clue) + +## 1.1.0 (2019-02-07) + +* New UV based event loop (ext-uv). + (#112 by @WyriHaximus) + +* Use high resolution timer on PHP 7.3+. + (#182 by @clue) + +* Improve PCNTL signals by using async signal dispatching if available. + (#179 by @CharlotteDunois) + +* Improve test suite and test suite set up. + (#174 by @WyriHaximus, #181 by @clue) + +* Fix PCNTL signals edge case. + (#183 by @clue) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.5.3 release. + +## 0.5.3 (2018-07-09) + +* Improve performance by importing global functions. + (#167 by @Ocramius) + +* Improve test suite by simplifying test bootstrap by using dev autoloader. + (#169 by @lcobucci) + +* Minor internal changes to improved backward compatibility with PHP 5.3. + (#166 by @Donatello-za) + +## 0.5.2 (2018-04-24) + +* Feature: Improve memory consumption and runtime performance for `StreamSelectLoop` timers. + (#164 by @clue) + +* Improve test suite by removing I/O dependency at `StreamSelectLoopTest` to fix Mac OS X tests. + (#161 by @nawarian) + +## 0.5.1 (2018-04-09) + +* Feature: New `ExtEvLoop` (PECL ext-ev) (#148 by @kaduev13) + +## 0.5.0 (2018-04-05) + +A major feature release with a significant documentation overhaul and long overdue API cleanup! + +This update involves a number of BC breaks due to dropped support for deprecated +functionality. We've tried hard to avoid BC breaks where possible and minimize +impact otherwise. We expect that most consumers of this package will actually +not be affected by any BC breaks, see below for more details. + +We realize that the changes listed below may seem overwhelming, but we've tried +to be very clear about any possible BC breaks. Don't worry: In fact, all ReactPHP +components are already compatible and support both this new release as well as +providing backwards compatibility with the last release. + +* Feature / BC break: Add support for signal handling via new + `LoopInterface::addSignal()` and `LoopInterface::removeSignal()` methods. + (#104 by @WyriHaximus and #111 and #150 by @clue) + + ```php + $loop->addSignal(SIGINT, function () { + echo 'CTRL-C'; + }); + ``` + +* Feature: Significant documentation updates for `LoopInterface` and `Factory`. + (#100, #119, #126, #127, #159 and #160 by @clue, #113 by @WyriHaximus and #81 and #91 by @jsor) + +* Feature: Add examples to ease getting started + (#99, #100 and #125 by @clue, #59 by @WyriHaximus and #143 by @jsor) + +* Feature: Documentation for advanced timer concepts, such as monotonic time source vs wall-clock time + and high precision timers with millisecond accuracy or below. + (#130 and #157 by @clue) + +* Feature: Documentation for advanced stream concepts, such as edge-triggered event listeners + and stream buffers and allow throwing Exception if stream resource is not supported. + (#129 and #158 by @clue) + +* Feature: Throw `BadMethodCallException` on manual loop creation when required extension isn't installed. + (#153 by @WyriHaximus) + +* Feature / BC break: First class support for legacy PHP 5.3 through PHP 7.2 and HHVM + and remove all `callable` type hints for consistency reasons. + (#141 and #151 by @clue) + +* BC break: Documentation for timer API and clean up unneeded timer API. + (#102 by @clue) + + Remove `TimerInterface::cancel()`, use `LoopInterface::cancelTimer()` instead: + + ```php + // old (method invoked on timer instance) + $timer->cancel(); + + // already supported before: invoke method on loop instance + $loop->cancelTimer($timer); + ``` + + Remove unneeded `TimerInterface::setData()` and `TimerInterface::getData()`, + use closure binding to add arbitrary data to timer instead: + + ```php + // old (limited setData() and getData() only allows single variable) + $name = 'Tester'; + $timer = $loop->addTimer(1.0, function ($timer) { + echo 'Hello ' . $timer->getData() . PHP_EOL; + }); + $timer->setData($name); + + // already supported before: closure binding allows any number of variables + $name = 'Tester'; + $loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . PHP_EOL; + }); + ``` + + Remove unneeded `TimerInterface::getLoop()`, use closure binding instead: + + ```php + // old (getLoop() called on timer instance) + $loop->addTimer(0.1, function ($timer) { + $timer->getLoop()->stop(); + }); + + // already supported before: use closure binding as usual + $loop->addTimer(0.1, function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::isTimerActive()` and + `TimerInterface::isActive()` to reduce API surface. + (#133 by @clue) + + ```php + // old (method on timer instance or on loop instance) + $timer->isActive(); + $loop->isTimerActive($timer); + ``` + +* BC break: Move `TimerInterface` one level up to `React\EventLoop\TimerInterface`. + (#138 by @WyriHaximus) + + ```php + // old (notice obsolete "Timer" namespace) + assert($timer instanceof React\EventLoop\Timer\TimerInterface); + + // new + assert($timer instanceof React\EventLoop\TimerInterface); + ``` + +* BC break: Remove unneeded `LoopInterface::nextTick()` (and internal `NextTickQueue`), + use `LoopInterface::futureTick()` instead. + (#30 by @clue) + + ```php + // old (removed) + $loop->nextTick(function () { + echo 'tick'; + }); + + // already supported before + $loop->futureTick(function () { + echo 'tick'; + }); + ``` + +* BC break: Remove unneeded `$loop` argument for `LoopInterface::futureTick()` + (and fix internal cyclic dependency). + (#103 by @clue) + + ```php + // old ($loop gets passed by default) + $loop->futureTick(function ($loop) { + $loop->stop(); + }); + + // already supported before: use closure binding as usual + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::tick()`. + (#72 by @jsor) + + ```php + // old (removed) + $loop->tick(); + + // suggested work around for testing purposes only + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Documentation for advanced stream API and clean up unneeded stream API. + (#110 by @clue) + + Remove unneeded `$loop` argument for `LoopInterface::addReadStream()` + and `LoopInterface::addWriteStream()`, use closure binding instead: + + ```php + // old ($loop gets passed by default) + $loop->addReadStream($stream, function ($stream, $loop) { + $loop->removeReadStream($stream); + }); + + // already supported before: use closure binding as usual + $loop->addReadStream($stream, function ($stream) use ($loop) { + $loop->removeReadStream($stream); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::removeStream()` method, + use `LoopInterface::removeReadStream()` and `LoopInterface::removeWriteStream()` instead. + (#118 by @clue) + + ```php + // old + $loop->removeStream($stream); + + // already supported before + $loop->removeReadStream($stream); + $loop->removeWriteStream($stream); + ``` + +* BC break: Rename `LibEventLoop` to `ExtLibeventLoop` and `LibEvLoop` to `ExtLibevLoop` + for consistent naming for event loop implementations. + (#128 by @clue) + +* BC break: Remove optional `EventBaseConfig` argument from `ExtEventLoop` + and make its `FEATURE_FDS` enabled by default. + (#156 by @WyriHaximus) + +* BC break: Mark all classes as final to discourage inheritance. + (#131 by @clue) + +* Fix: Fix `ExtEventLoop` to keep track of stream resources (refcount) + (#123 by @clue) + +* Fix: Ensure large timer interval does not overflow on 32bit systems + (#132 by @clue) + +* Fix: Fix separately removing readable and writable side of stream when closing + (#139 by @clue) + +* Fix: Properly clean up event watchers for `ext-event` and `ext-libev` + (#149 by @clue) + +* Fix: Minor code cleanup and remove unneeded references + (#145 by @seregazhuk) + +* Fix: Discourage outdated `ext-libevent` on PHP 7 + (#62 by @cboden) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and PHPUnit 5, + lock Travis distro so new defaults will not break the build, + improve test suite to be less fragile and increase test timeouts, + test against PHP 7.2 and reduce fwrite() call length to one chunk. + (#106 and #144 by @clue, #120 and #124 by @carusogabriel, #147 by nawarian and #92 by @kelunik) + +* A number of changes were originally planned for this release but have been backported + to the last `v0.4.3` already: #74, #76, #79, #81 (refs #65, #66, #67), #88 and #93 + +## 0.4.3 (2017-04-27) + +* Bug fix: Bugfix in the usage sample code #57 (@dandelionred) +* Improvement: Remove branch-alias definition #53 (@WyriHaximus) +* Improvement: StreamSelectLoop: Use fresh time so Timers added during stream events are accurate #51 (@andrewminerd) +* Improvement: Avoid deprecation warnings in test suite due to deprecation of getMock() in PHPUnit #68 (@martinschroeder) +* Improvement: Add PHPUnit 4.8 to require-dev #69 (@shaunbramley) +* Improvement: Increase test timeouts for HHVM and unify timeout handling #70 (@clue) +* Improvement: Travis improvements (backported from #74) #75 (@clue) +* Improvement: Test suite now uses socket pairs instead of memory streams #66 (@martinschroeder) +* Improvement: StreamSelectLoop: Test suite uses signal constant names in data provider #67 (@martinschroeder) +* Improvement: ExtEventLoop: No longer suppress all errors #65 (@mamciek) +* Improvement: Readme cleanup #89 (@jsor) +* Improvement: Restructure and improve README #90 (@jsor) +* Bug fix: StreamSelectLoop: Fix erroneous zero-time sleep (backport to 0.4) #94 (@jsor) + +## 0.4.2 (2016-03-07) + +* Bug fix: No longer error when signals sent to StreamSelectLoop +* Support HHVM and PHP7 (@ondrejmirtes, @cebe) +* Feature: Added support for EventConfig for ExtEventLoop (@steverhoades) +* Bug fix: Fixed an issue loading loop extension libs via autoloader (@czarpino) + +## 0.4.1 (2014-04-13) + +* Bug fix: null timeout in StreamSelectLoop causing 100% CPU usage (@clue) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.4.0 (2014-02-02) + +* Feature: Added `EventLoopInterface::nextTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `EventLoopInterface::futureTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `ExtEventLoop` implementation using pecl/event (@jmalloc) +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: New method: `EventLoopInterface::nextTick()` +* BC break: New method: `EventLoopInterface::futureTick()` +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.5 (2016-12-28) + +This is a compatibility release that eases upgrading to the v0.4 release branch. +You should consider upgrading to the v0.4 release branch. + +* Feature: Cap min timer interval at 1µs, thus improving compatibility with v0.4 + (#47 by @clue) + +## 0.3.4 (2014-03-30) + +* Bug fix: Changed StreamSelectLoop to use non-blocking behavior on tick() (@astephens25) + +## 0.3.3 (2013-07-08) + +* Bug fix: No error on removing non-existent streams (@clue) +* Bug fix: Do not silently remove feof listeners in `LibEvLoop` + +## 0.3.0 (2013-04-14) + +* BC break: New timers API (@nrk) +* BC break: Remove check on return value from stream callbacks (@nrk) + +## 0.2.7 (2013-01-05) + +* Bug fix: Fix libevent timers with PHP 5.3 +* Bug fix: Fix libevent timer cancellation (@nrk) + +## 0.2.6 (2012-12-26) + +* Bug fix: Plug memory issue in libevent timers (@cameronjacobson) +* Bug fix: Correctly pause LibEvLoop on stop() + +## 0.2.3 (2012-11-14) + +* Feature: LibEvLoop, integration of `php-libev` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/trilhas_poo/vendor/react/event-loop/LICENSE b/trilhas_poo/vendor/react/event-loop/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/event-loop/README.md b/trilhas_poo/vendor/react/event-loop/README.md new file mode 100644 index 0000000..bbdf1cf --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/README.md @@ -0,0 +1,930 @@ +# EventLoop + +[![CI status](https://github.com/reactphp/event-loop/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/event-loop/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/event-loop?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/event-loop) + +[ReactPHP](https://reactphp.org/)'s core reactor event loop that libraries can use for evented I/O. + +In order for async based libraries to be interoperable, they need to use the +same event loop. This component provides a common `LoopInterface` that any +library can target. This allows them to be used in the same loop, with one +single [`run()`](#run) call that is controlled by the user. + +**Table of contents** + +* [Quickstart example](#quickstart-example) +* [Usage](#usage) + * [Loop](#loop) + * [Loop methods](#loop-methods) + * [Loop autorun](#loop-autorun) + * [get()](#get) + * [~~Factory~~](#factory) + * [~~create()~~](#create) + * [Loop implementations](#loop-implementations) + * [StreamSelectLoop](#streamselectloop) + * [ExtEventLoop](#exteventloop) + * [ExtEvLoop](#extevloop) + * [ExtUvLoop](#extuvloop) + * [~~ExtLibeventLoop~~](#extlibeventloop) + * [~~ExtLibevLoop~~](#extlibevloop) + * [LoopInterface](#loopinterface) + * [run()](#run) + * [stop()](#stop) + * [addTimer()](#addtimer) + * [addPeriodicTimer()](#addperiodictimer) + * [cancelTimer()](#canceltimer) + * [futureTick()](#futuretick) + * [addSignal()](#addsignal) + * [removeSignal()](#removesignal) + * [addReadStream()](#addreadstream) + * [addWriteStream()](#addwritestream) + * [removeReadStream()](#removereadstream) + * [removeWriteStream()](#removewritestream) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Quickstart example + +Here is an async HTTP server built with just the event loop. + +```php +addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); + +$loop->run(); +``` + +While the former is more concise, the latter is more explicit. +In both cases, the program would perform the exact same steps. + +1. The event loop instance is created at the beginning of the program. This is + implicitly done the first time you call the [`Loop` class](#loop) or + explicitly when using the deprecated [`Factory::create()` method](#create) + (or manually instantiating any of the [loop implementations](#loop-implementations)). +2. The event loop is used directly or passed as an instance to library and + application code. In this example, a periodic timer is registered with the + event loop which simply outputs `Tick` every fraction of a second until another + timer stops the periodic timer after a second. +3. The event loop is run at the end of the program. This is automatically done + when using the [`Loop` class](#loop) or explicitly with a single [`run()`](#run) + call at the end of the program. + +As of `v1.2.0`, we highly recommend using the [`Loop` class](#loop). +The explicit loop instructions are still valid and may still be useful in some +applications, especially for a transition period towards the more concise style. + +### Loop + +The `Loop` class exists as a convenient global accessor for the event loop. + +#### Loop methods + +The `Loop` class provides all methods that exist on the [`LoopInterface`](#loopinterface) +as static methods: + +* [run()](#run) +* [stop()](#stop) +* [addTimer()](#addtimer) +* [addPeriodicTimer()](#addperiodictimer) +* [cancelTimer()](#canceltimer) +* [futureTick()](#futuretick) +* [addSignal()](#addsignal) +* [removeSignal()](#removesignal) +* [addReadStream()](#addreadstream) +* [addWriteStream()](#addwritestream) +* [removeReadStream()](#removereadstream) +* [removeWriteStream()](#removewritestream) + +If you're working with the event loop in your application code, it's often +easiest to directly interface with the static methods defined on the `Loop` class +like this: + +```php +use React\EventLoop\Loop; + +$timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +On the other hand, if you're familiar with object-oriented programming (OOP) and +dependency injection (DI), you may want to inject an event loop instance and +invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +Each static method call will be forwarded as-is to the underlying event loop +instance by using the [`Loop::get()`](#get) call internally. +See [`LoopInterface`](#loopinterface) for more details about available methods. + +#### Loop autorun + +When using the `Loop` class, it will automatically execute the loop at the end of +the program. This means the following example will schedule a timer and will +automatically execute the program until the timer event fires: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(1.0, function () { + echo 'Hello' . PHP_EOL; +}); +``` + +As of `v1.2.0`, we highly recommend using the `Loop` class this way and omitting any +explicit [`run()`](#run) calls. For BC reasons, the explicit [`run()`](#run) +method is still valid and may still be useful in some applications, especially +for a transition period towards the more concise style. + +If you don't want the `Loop` to run automatically, you can either explicitly +[`run()`](#run) or [`stop()`](#stop) it. This can be useful if you're using +a global exception handler like this: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(10.0, function () { + echo 'Never happens'; +}); + +set_exception_handler(function (Throwable $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; + Loop::stop(); +}); + +throw new RuntimeException('Demo'); +``` + +#### get() + +The `get(): LoopInterface` method can be used to +get the currently active event loop instance. + +This method will always return the same event loop instance throughout the +lifetime of your application. + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +$loop = Loop::get(); + +assert($loop instanceof LoopInterface); +assert($loop === Loop::get()); +``` + +This is particularly useful if you're using object-oriented programming (OOP) +and dependency injection (DI). In this case, you may want to inject an event +loop instance and invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +See [`LoopInterface`](#loopinterface) for more details about available methods. + +### ~~Factory~~ + +> Deprecated since v1.2.0, see [`Loop` class](#loop) instead. + +The deprecated `Factory` class exists as a convenient way to pick the best available +[event loop implementation](#loop-implementations). + +#### ~~create()~~ + +> Deprecated since v1.2.0, see [`Loop::get()`](#get) instead. + +The deprecated `create(): LoopInterface` method can be used to +create a new event loop instance: + +```php +// deprecated +$loop = React\EventLoop\Factory::create(); + +// new +$loop = React\EventLoop\Loop::get(); +``` + +This method always returns an instance implementing [`LoopInterface`](#loopinterface), +the actual [event loop implementation](#loop-implementations) is an implementation detail. + +This method should usually only be called once at the beginning of the program. + +### Loop implementations + +In addition to the [`LoopInterface`](#loopinterface), there are a number of +event loop implementations provided. + +All of the event loops support these features: + +* File descriptor polling +* One-off timers +* Periodic timers +* Deferred execution on future loop tick + +For most consumers of this package, the underlying event loop implementation is +an implementation detail. +You should use the [`Loop` class](#loop) to automatically create a new instance. + +Advanced! If you explicitly need a certain event loop implementation, you can +manually instantiate one of the following classes. +Note that you may have to install the required PHP extensions for the respective +event loop implementation first or they will throw a `BadMethodCallException` on creation. + +#### StreamSelectLoop + +A `stream_select()` based event loop. + +This uses the [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) +function and is the only implementation that works out of the box with PHP. + +This event loop works out of the box on PHP 5.3 through PHP 8+ and HHVM. +This means that no installation is required and this library works on all +platforms and supported PHP versions. +Accordingly, the [`Loop` class](#loop) and the deprecated [`Factory`](#factory) +will use this event loop by default if you do not install any of the event loop +extensions listed below. + +Under the hood, it does a simple `select` system call. +This system call is limited to the maximum file descriptor number of +`FD_SETSIZE` (platform dependent, commonly 1024) and scales with `O(m)` +(`m` being the maximum file descriptor number passed). +This means that you may run into issues when handling thousands of streams +concurrently and you may want to look into using one of the alternative +event loop implementations listed below in this case. +If your use case is among the many common use cases that involve handling only +dozens or a few hundred streams at once, then this event loop implementation +performs really well. + +If you want to use signal handling (see also [`addSignal()`](#addsignal) below), +this event loop implementation requires `ext-pcntl`. +This extension is only available for Unix-like platforms and does not support +Windows. +It is commonly installed as part of many PHP distributions. +If this extension is missing (or you're running on Windows), signal handling is +not supported and throws a `BadMethodCallException` instead. + +This event loop is known to rely on wall-clock time to schedule future timers +when using any version before PHP 7.3, because a monotonic time source is +only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and +then adjust your system time forward by 20s, the timer may trigger in 10s. +See also [`addTimer()`](#addtimer) for more details. + +#### ExtEventLoop + +An `ext-event` based event loop. + +This uses the [`event` PECL extension](https://pecl.php.net/package/event), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 5.4 through PHP 8+. + +#### ExtEvLoop + +An `ext-ev` based event loop. + +This loop uses the [`ev` PECL extension](https://pecl.php.net/package/ev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + + +This loop is known to work with PHP 5.4 through PHP 8+. + +#### ExtUvLoop + +An `ext-uv` based event loop. + +This loop uses the [`uv` PECL extension](https://pecl.php.net/package/uv), +that provides an interface to `libuv` library. +`libuv` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 7+. + +#### ~~ExtLibeventLoop~~ + +> Deprecated since v1.2.0, use [`ExtEventLoop`](#exteventloop) instead. + +An `ext-libevent` based event loop. + +This uses the [`libevent` PECL extension](https://pecl.php.net/package/libevent), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This event loop does only work with PHP 5. +An [unofficial update](https://github.com/php/pecl-event-libevent/pull/2) for +PHP 7 does exist, but it is known to cause regular crashes due to `SEGFAULT`s. +To reiterate: Using this event loop on PHP 7 is not recommended. +Accordingly, neither the [`Loop` class](#loop) nor the deprecated +[`Factory` class](#factory) will try to use this event loop on PHP 7. + +This event loop is known to trigger a readable listener only if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. +See also [`addReadStream()`](#addreadstream) for more details. + +#### ~~ExtLibevLoop~~ + +> Deprecated since v1.2.0, use [`ExtEvLoop`](#extevloop) instead. + +An `ext-libev` based event loop. + +This uses an [unofficial `libev` extension](https://github.com/m4rw3r/php-libev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + +This loop does only work with PHP 5. +An update for PHP 7 is [unlikely](https://github.com/m4rw3r/php-libev/issues/8) +to happen any time soon. + +### LoopInterface + +#### run() + +The `run(): void` method can be used to +run the event loop until there are no more tasks to perform. + +For many applications, this method is the only directly visible +invocation on the event loop. +As a rule of thumb, it is usually recommended to attach everything to the +same loop instance and then run the loop once at the bottom end of the +application. + +```php +$loop->run(); +``` + +This method will keep the loop running until there are no more tasks +to perform. In other words: This method will block until the last +timer, stream and/or signal has been removed. + +Likewise, it is imperative to ensure the application actually invokes +this method once. Adding listeners to the loop and missing to actually +run it will result in the application exiting without actually waiting +for any of the attached listeners. + +This method MUST NOT be called while the loop is already running. +This method MAY be called more than once after it has explicitly been +[`stop()`ped](#stop) or after it automatically stopped because it +previously did no longer have anything to do. + +#### stop() + +The `stop(): void` method can be used to +instruct a running event loop to stop. + +This method is considered advanced usage and should be used with care. +As a rule of thumb, it is usually recommended to let the loop stop +only automatically when it no longer has anything to do. + +This method can be used to explicitly instruct the event loop to stop: + +```php +$loop->addTimer(3.0, function () use ($loop) { + $loop->stop(); +}); +``` + +Calling this method on a loop instance that is not currently running or +on a loop instance that has already been stopped has no effect. + +#### addTimer() + +The `addTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked once after the given interval. + +The second parameter MUST be a timer callback function that accepts +the timer instance as its only parameter. +If you don't use the timer instance inside your timer callback function +you MAY use a function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +This method returns a timer instance. The same timer instance will also be +passed into the timer callback function as described above. +You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. +Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure +the callback will be invoked only once after the given interval. + +```php +$loop->addTimer(0.8, function () { + echo 'world!' . PHP_EOL; +}); + +$loop->addTimer(0.3, function () { + echo 'hello '; +}); +``` + +See also [example #1](examples). + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->addTimer(1.0, function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +#### addPeriodicTimer() + +The `addPeriodicTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked repeatedly after the given interval. + +The second parameter MUST be a timer callback function that accepts +the timer instance as its only parameter. +If you don't use the timer instance inside your timer callback function +you MAY use a function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +This method returns a timer instance. The same timer instance will also be +passed into the timer callback function as described above. +Unlike [`addTimer()`](#addtimer), this method will ensure the callback +will be invoked infinitely after the given interval or until you invoke +[`cancelTimer`](#canceltimer). + +```php +$timer = $loop->addPeriodicTimer(0.1, function () { + echo 'tick!' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +See also [example #2](examples). + +If you want to limit the number of executions, you can bind +arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $n = 3; + $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + if ($n > 0) { + --$n; + echo "hello $name\n"; + } else { + $loop->cancelTimer($timer); + } + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +Additionally, periodic timers may be subject to timer drift due to +re-scheduling after each invocation. As such, it's generally not +recommended to rely on this for high precision intervals with millisecond +accuracy or below. + +#### cancelTimer() + +The `cancelTimer(TimerInterface $timer): void` method can be used to +cancel a pending timer. + +See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + +Calling this method on a timer instance that has not been added to this +loop instance or on a timer that has already been cancelled has no effect. + +#### futureTick() + +The `futureTick(callable $listener): void` method can be used to +schedule a callback to be invoked on a future tick of the event loop. + +This works very much similar to timers with an interval of zero seconds, +but does not require the overhead of scheduling a timer queue. + +The tick callback function MUST be able to accept zero parameters. + +The tick callback function MUST NOT throw an `Exception`. +The return value of the tick callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->futureTick(function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +Unlike timers, tick callbacks are guaranteed to be executed in the order +they are enqueued. +Also, once a callback is enqueued, there's no way to cancel this operation. + +This is often used to break down bigger tasks into smaller steps (a form +of cooperative multitasking). + +```php +$loop->futureTick(function () { + echo 'b'; +}); +$loop->futureTick(function () { + echo 'c'; +}); +echo 'a'; +``` + +See also [example #3](examples). + +#### addSignal() + +The `addSignal(int $signal, callable $listener): void` method can be used to +register a listener to be notified when a signal has been caught by this process. + +This is useful to catch user interrupt signals or shutdown signals from +tools like `supervisor` or `systemd`. + +The second parameter MUST be a listener callback function that accepts +the signal as its only parameter. +If you don't use the signal inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +```php +$loop->addSignal(SIGINT, function (int $signal) { + echo 'Caught user interrupt signal' . PHP_EOL; +}); +``` + +See also [example #4](examples). + +Signaling is only available on Unix-like platforms, Windows isn't +supported due to operating system limitations. +This method may throw a `BadMethodCallException` if signals aren't +supported on this platform, for example when required extensions are +missing. + +**Note: A listener can only be added once to the same signal, any +attempts to add it more than once will be ignored.** + +#### removeSignal() + +The `removeSignal(int $signal, callable $listener): void` method can be used to +remove a previously added signal listener. + +```php +$loop->removeSignal(SIGINT, $listener); +``` + +Any attempts to remove listeners that aren't registered will be ignored. + +#### addReadStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [readable Stream API](https://github.com/reactphp/stream#readablestreaminterface) + instead. + +The `addReadStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to read. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to read by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeReadStream()`](#removereadstream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The second parameter MUST be a listener callback function that accepts +the stream resource as its only parameter. +If you don't use the stream resource inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addReadStream($stream, function ($stream) use ($name) { + echo $name . ' said: ' . fread($stream); +}); +``` + +See also [example #11](examples). + +You can invoke [`removeReadStream()`](#removereadstream) to remove the +read event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +Some event loop implementations are known to only trigger the listener if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. + +#### addWriteStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + instead. + +The `addWriteStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to write. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to write by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeWriteStream()`](#removewritestream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The second parameter MUST be a listener callback function that accepts +the stream resource as its only parameter. +If you don't use the stream resource inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addWriteStream($stream, function ($stream) use ($name) { + fwrite($stream, 'Hello ' . $name); +}); +``` + +See also [example #12](examples). + +You can invoke [`removeWriteStream()`](#removewritestream) to remove the +write event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +#### removeReadStream() + +The `removeReadStream(resource $stream): void` method can be used to +remove the read event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +#### removeWriteStream() + +The `removeWriteStream(resource $stream): void` method can be used to +remove the write event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/event-loop:^1.6 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +Installing any of the event loop extensions is suggested, but entirely optional. +See also [event loop implementations](#loop-implementations) for more details. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See our [Stream component](https://github.com/reactphp/stream) for more + information on how streams are used in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/event-loop/dependents) + for a list of packages that use the EventLoop in real-world applications. diff --git a/trilhas_poo/vendor/react/event-loop/composer.json b/trilhas_poo/vendor/react/event-loop/composer.json new file mode 100644 index 0000000..25a41fe --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/composer.json @@ -0,0 +1,47 @@ +{ + "name": "react/event-loop", + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": ["event-loop", "asynchronous"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\EventLoop\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/ExtEvLoop.php b/trilhas_poo/vendor/react/event-loop/src/ExtEvLoop.php new file mode 100644 index 0000000..7689ff5 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/ExtEvLoop.php @@ -0,0 +1,253 @@ +loop = new EvLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + + public function addReadStream($stream, $listener) + { + $key = (int)$stream; + + if (isset($this->readStreams[$key])) { + return; + } + + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::READ, $callback); + $this->readStreams[$key] = $event; + } + + /** + * @param resource $stream + * @param callable $listener + * + * @return \Closure + */ + private function getStreamListenerClosure($stream, $listener) + { + return function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + } + + public function addWriteStream($stream, $listener) + { + $key = (int)$stream; + + if (isset($this->writeStreams[$key])) { + return; + } + + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::WRITE, $callback); + $this->writeStreams[$key] = $event; + } + + public function removeReadStream($stream) + { + $key = (int)$stream; + + if (!isset($this->readStreams[$key])) { + return; + } + + $this->readStreams[$key]->stop(); + unset($this->readStreams[$key]); + } + + public function removeWriteStream($stream) + { + $key = (int)$stream; + + if (!isset($this->writeStreams[$key])) { + return; + } + + $this->writeStreams[$key]->stop(); + unset($this->writeStreams[$key]); + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $that = $this; + $timers = $this->timers; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->offsetExists($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = $this->loop->timer($timer->getInterval(), 0.0, $callback); + $this->timers->offsetSet($timer, $event); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $event = $this->loop->timer($timer->getInterval(), $timer->getInterval(), $callback); + $this->timers->offsetSet($timer, $event); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if (!isset($this->timers[$timer])) { + return; + } + + $event = $this->timers[$timer]; + $event->stop(); + $this->timers->offsetUnset($timer); + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams + && !$this->writeStreams + && !$this->timers->count() + && $this->signals->isEmpty(); + + $flags = Ev::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags |= Ev::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + + $this->loop->run($flags); + } + } + + public function stop() + { + $this->running = false; + } + + public function __destruct() + { + /** @var TimerInterface $timer */ + foreach ($this->timers as $timer) { + $this->cancelTimer($timer); + } + + foreach ($this->readStreams as $key => $stream) { + $this->removeReadStream($key); + } + + foreach ($this->writeStreams as $key => $stream) { + $this->removeWriteStream($key); + } + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = $this->loop->signal($signal, function() use ($signal) { + $this->signals->call($signal); + }); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal]->stop(); + unset($this->signalEvents[$signal]); + } + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/ExtEventLoop.php b/trilhas_poo/vendor/react/event-loop/src/ExtEventLoop.php new file mode 100644 index 0000000..2f26d74 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/ExtEventLoop.php @@ -0,0 +1,275 @@ +requireFeatures(\EventConfig::FEATURE_FDS); + } + + $this->eventBase = new EventBase($config); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + + $this->createTimerCallback(); + $this->createStreamCallback(); + } + + public function __destruct() + { + // explicitly clear all references to Event objects to prevent SEGFAULTs on Windows + foreach ($this->timerEvents as $timer) { + $this->timerEvents->offsetUnset($timer); + } + + $this->readEvents = array(); + $this->writeEvents = array(); + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::READ, $this->streamCallback); + $event->add(); + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->readRefs[$key] = $stream; + } + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::WRITE, $this->streamCallback); + $event->add(); + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->writeRefs[$key] = $stream; + } + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->free(); + unset( + $this->readEvents[$key], + $this->readListeners[$key], + $this->readRefs[$key] + ); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->free(); + unset( + $this->writeEvents[$key], + $this->writeListeners[$key], + $this->writeRefs[$key] + ); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->offsetExists($timer)) { + $this->timerEvents[$timer]->free(); + $this->timerEvents->offsetUnset($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = Event::signal($this->eventBase, $signal, array($this->signals, 'call')); + $this->signalEvents[$signal]->add(); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->free(); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = EventBase::LOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventBase::LOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + $this->eventBase->loop($flags); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $flags = Event::TIMEOUT; + + if ($timer->isPeriodic()) { + $flags |= Event::PERSIST; + } + + $event = new Event($this->eventBase, -1, $flags, $this->timerCallback, $timer); + $this->timerEvents[$timer] = $event; + + $event->add($timer->getInterval()); + } + + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use ($timers) { + \call_user_func($timer->getCallback(), $timer); + + if (!$timer->isPeriodic() && $timers->offsetExists($timer)) { + $this->cancelTimer($timer); + } + }; + } + + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use (&$read, &$write) { + $key = (int) $stream; + + if (Event::READ === (Event::READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + + if (Event::WRITE === (Event::WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/ExtLibevLoop.php b/trilhas_poo/vendor/react/event-loop/src/ExtLibevLoop.php new file mode 100644 index 0000000..c303fdd --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/ExtLibevLoop.php @@ -0,0 +1,201 @@ +loop = new EventLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + + public function addReadStream($stream, $listener) + { + if (isset($this->readEvents[(int) $stream])) { + return; + } + + $callback = function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + + $event = new IOEvent($callback, $stream, IOEvent::READ); + $this->loop->add($event); + + $this->readEvents[(int) $stream] = $event; + } + + public function addWriteStream($stream, $listener) + { + if (isset($this->writeEvents[(int) $stream])) { + return; + } + + $callback = function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + + $event = new IOEvent($callback, $stream, IOEvent::WRITE); + $this->loop->add($event); + + $this->writeEvents[(int) $stream] = $event; + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->stop(); + $this->loop->remove($this->readEvents[$key]); + unset($this->readEvents[$key]); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->stop(); + $this->loop->remove($this->writeEvents[$key]); + unset($this->writeEvents[$key]); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer( $interval, $callback, false); + + $that = $this; + $timers = $this->timerEvents; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = new TimerEvent($callback, $timer->getInterval()); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $event = new TimerEvent($callback, $timer->getInterval(), $timer->getInterval()); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timerEvents[$timer])) { + $this->loop->remove($this->timerEvents[$timer]); + $this->timerEvents->detach($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = new SignalEvent(function () use ($signals, $signal) { + $signals->call($signal); + }, $signal); + $this->loop->add($this->signalEvents[$signal]); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->stop(); + $this->loop->remove($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = EventLoop::RUN_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventLoop::RUN_NOWAIT; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + $this->loop->run($flags); + } + } + + public function stop() + { + $this->running = false; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/ExtLibeventLoop.php b/trilhas_poo/vendor/react/event-loop/src/ExtLibeventLoop.php new file mode 100644 index 0000000..099293a --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/ExtLibeventLoop.php @@ -0,0 +1,285 @@ +eventBase = \event_base_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + + $this->createTimerCallback(); + $this->createStreamCallback(); + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_READ, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_WRITE, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readListeners[$key])) { + $event = $this->readEvents[$key]; + \event_del($event); + \event_free($event); + + unset( + $this->readEvents[$key], + $this->readListeners[$key] + ); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeListeners[$key])) { + $event = $this->writeEvents[$key]; + \event_del($event); + \event_free($event); + + unset( + $this->writeEvents[$key], + $this->writeListeners[$key] + ); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->contains($timer)) { + $event = $this->timerEvents[$timer]; + \event_del($event); + \event_free($event); + + $this->timerEvents->detach($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = \event_new(); + \event_set($this->signalEvents[$signal], $signal, \EV_PERSIST | \EV_SIGNAL, array($this->signals, 'call')); + \event_base_set($this->signalEvents[$signal], $this->eventBase); + \event_add($this->signalEvents[$signal]); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \event_del($this->signalEvents[$signal]); + \event_free($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = \EVLOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= \EVLOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + \event_base_loop($this->eventBase, $flags); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $this->timerEvents[$timer] = $event = \event_timer_new(); + + \event_timer_set($event, $this->timerCallback, $timer); + \event_base_set($event, $this->eventBase); + \event_add($event, $timer->getInterval() * self::MICROSECONDS_PER_SECOND); + } + + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $that = $this; + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use ($timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + // Timer already cancelled ... + if (!$timers->contains($timer)) { + return; + } + + // Reschedule periodic timers ... + if ($timer->isPeriodic()) { + \event_add( + $timers[$timer], + $timer->getInterval() * ExtLibeventLoop::MICROSECONDS_PER_SECOND + ); + + // Clean-up one shot timers ... + } else { + $that->cancelTimer($timer); + } + }; + } + + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use (&$read, &$write) { + $key = (int) $stream; + + if (\EV_READ === (\EV_READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + + if (\EV_WRITE === (\EV_WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/ExtUvLoop.php b/trilhas_poo/vendor/react/event-loop/src/ExtUvLoop.php new file mode 100644 index 0000000..29aa86b --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/ExtUvLoop.php @@ -0,0 +1,350 @@ +uv = \uv_loop_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->streamListener = $this->createStreamListener(); + $this->signals = new SignalsHandler(); + } + + /** + * Returns the underlying ext-uv event loop. (Internal ReactPHP use only.) + * + * @internal + * + * @return resource + */ + public function getUvLoop() + { + return $this->uv; + } + + /** + * {@inheritdoc} + */ + public function addReadStream($stream, $listener) + { + if (isset($this->readStreams[(int) $stream])) { + return; + } + + $this->readStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + + /** + * {@inheritdoc} + */ + public function addWriteStream($stream, $listener) + { + if (isset($this->writeStreams[(int) $stream])) { + return; + } + + $this->writeStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + + /** + * {@inheritdoc} + */ + public function removeReadStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + unset($this->readStreams[(int) $stream]); + $this->removeStream($stream); + } + + /** + * {@inheritdoc} + */ + public function removeWriteStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + unset($this->writeStreams[(int) $stream]); + $this->removeStream($stream); + } + + /** + * {@inheritdoc} + */ + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $that = $this; + $timers = $this->timers; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->offsetExists($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = \uv_timer_init($this->uv); + $this->timers->offsetSet($timer, $event); + \uv_timer_start( + $event, + $this->convertFloatSecondsToMilliseconds($interval), + 0, + $callback + ); + + return $timer; + } + + /** + * {@inheritdoc} + */ + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $interval = $this->convertFloatSecondsToMilliseconds($interval); + $event = \uv_timer_init($this->uv); + $this->timers->offsetSet($timer, $event); + \uv_timer_start( + $event, + $interval, + (int) $interval === 0 ? 1 : $interval, + $callback + ); + + return $timer; + } + + /** + * {@inheritdoc} + */ + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timers[$timer])) { + @\uv_timer_stop($this->timers[$timer]); + $this->timers->offsetUnset($timer); + } + } + + /** + * {@inheritdoc} + */ + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = \uv_signal_init($this->uv); + \uv_signal_start($this->signalEvents[$signal], function () use ($signals, $signal) { + $signals->call($signal); + }, $signal); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \uv_signal_stop($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + /** + * {@inheritdoc} + */ + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams + && !$this->writeStreams + && !$this->timers->count() + && $this->signals->isEmpty(); + + // Use UV::RUN_ONCE when there are only I/O events active in the loop and block until one of those triggers, + // otherwise use UV::RUN_NOWAIT. + // @link http://docs.libuv.org/en/v1.x/loop.html#c.uv_run + $flags = \UV::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags = \UV::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + + \uv_run($this->uv, $flags); + } + } + + /** + * {@inheritdoc} + */ + public function stop() + { + $this->running = false; + } + + private function addStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + $this->streamEvents[(int)$stream] = \uv_poll_init_socket($this->uv, $stream); + } + + if ($this->streamEvents[(int) $stream] !== false) { + $this->pollStream($stream); + } + } + + private function removeStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + if (!isset($this->readStreams[(int) $stream]) + && !isset($this->writeStreams[(int) $stream])) { + \uv_poll_stop($this->streamEvents[(int) $stream]); + \uv_close($this->streamEvents[(int) $stream]); + unset($this->streamEvents[(int) $stream]); + return; + } + + $this->pollStream($stream); + } + + private function pollStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + $flags = 0; + if (isset($this->readStreams[(int) $stream])) { + $flags |= \UV::READABLE; + } + + if (isset($this->writeStreams[(int) $stream])) { + $flags |= \UV::WRITABLE; + } + + \uv_poll_start($this->streamEvents[(int) $stream], $flags, $this->streamListener); + } + + /** + * Create a stream listener + * + * @return callable Returns a callback + */ + private function createStreamListener() + { + $callback = function ($event, $status, $events, $stream) { + // libuv automatically stops polling on error, re-enable polling to match other loop implementations + if ($status !== 0) { + $this->pollStream($stream); + + // libuv may report no events on error, but this should still invoke stream listeners to report closed connections + // re-enable both readable and writable, correct listeners will be checked below anyway + if ($events === 0) { + $events = \UV::READABLE | \UV::WRITABLE; + } + } + + if (isset($this->readStreams[(int) $stream]) && ($events & \UV::READABLE)) { + \call_user_func($this->readStreams[(int) $stream], $stream); + } + + if (isset($this->writeStreams[(int) $stream]) && ($events & \UV::WRITABLE)) { + \call_user_func($this->writeStreams[(int) $stream], $stream); + } + }; + + return $callback; + } + + /** + * @param float $interval + * @return int + */ + private function convertFloatSecondsToMilliseconds($interval) + { + if ($interval < 0) { + return 0; + } + + $maxValue = (int) (\PHP_INT_MAX / 1000); + $intervalOverflow = false; + if (PHP_VERSION_ID > 80499 && $interval >= \PHP_INT_MAX + 1) { + $intervalOverflow = true; + } else { + $intInterval = (int) $interval; + if (($intInterval <= 0 && $interval > 1) || $intInterval >= $maxValue) { + $intervalOverflow = true; + } + } + + if ($intervalOverflow) { + throw new \InvalidArgumentException( + "Interval overflow, value must be lower than '{$maxValue}', but '{$interval}' passed." + ); + } + + return (int) \floor($interval * 1000); + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/Factory.php b/trilhas_poo/vendor/react/event-loop/src/Factory.php new file mode 100644 index 0000000..30bbfd7 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/Factory.php @@ -0,0 +1,75 @@ +futureTick(function () use (&$hasRun) { + $hasRun = true; + }); + + $stopped =& self::$stopped; + register_shutdown_function(function () use ($loop, &$hasRun, &$stopped) { + // Don't run if we're coming from a fatal error (uncaught exception). + $error = error_get_last(); + if ((isset($error['type']) ? $error['type'] : 0) & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)) { + return; + } + + if (!$hasRun && !$stopped) { + $loop->run(); + } + }); + // @codeCoverageIgnoreEnd + + return self::$instance; + } + + /** + * Internal undocumented method, behavior might change or throw in the + * future. Use with caution and at your own risk. + * + * @internal + * @return void + */ + public static function set(LoopInterface $loop) + { + self::$instance = $loop; + } + + /** + * [Advanced] Register a listener to be notified when a stream is ready to read. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addReadStream() + */ + public static function addReadStream($stream, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->addReadStream($stream, $listener); + } + + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addWriteStream() + */ + public static function addWriteStream($stream, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->addWriteStream($stream, $listener); + } + + /** + * Remove the read event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeReadStream() + */ + public static function removeReadStream($stream) + { + if (self::$instance !== null) { + self::$instance->removeReadStream($stream); + } + } + + /** + * Remove the write event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeWriteStream() + */ + public static function removeWriteStream($stream) + { + if (self::$instance !== null) { + self::$instance->removeWriteStream($stream); + } + } + + /** + * Enqueue a callback to be invoked once after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addTimer() + */ + public static function addTimer($interval, $callback) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + return self::$instance->addTimer($interval, $callback); + } + + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addPeriodicTimer() + */ + public static function addPeriodicTimer($interval, $callback) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + return self::$instance->addPeriodicTimer($interval, $callback); + } + + /** + * Cancel a pending timer. + * + * @param TimerInterface $timer + * @return void + * @see LoopInterface::cancelTimer() + */ + public static function cancelTimer(TimerInterface $timer) + { + if (self::$instance !== null) { + self::$instance->cancelTimer($timer); + } + } + + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * @param callable $listener + * @return void + * @see LoopInterface::futureTick() + */ + public static function futureTick($listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + + self::$instance->futureTick($listener); + } + + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::addSignal() + */ + public static function addSignal($signal, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + + self::$instance->addSignal($signal, $listener); + } + + /** + * Removes a previously added signal listener. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::removeSignal() + */ + public static function removeSignal($signal, $listener) + { + if (self::$instance !== null) { + self::$instance->removeSignal($signal, $listener); + } + } + + /** + * Run the event loop until there are no more tasks to perform. + * + * @return void + * @see LoopInterface::run() + */ + public static function run() + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + + self::$instance->run(); + } + + /** + * Instruct a running event loop to stop. + * + * @return void + * @see LoopInterface::stop() + */ + public static function stop() + { + self::$stopped = true; + if (self::$instance !== null) { + self::$instance->stop(); + } + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/LoopInterface.php b/trilhas_poo/vendor/react/event-loop/src/LoopInterface.php new file mode 100644 index 0000000..9266f71 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/LoopInterface.php @@ -0,0 +1,472 @@ +addReadStream($stream, function ($stream) use ($name) { + * echo $name . ' said: ' . fread($stream); + * }); + * ``` + * + * See also [example #11](examples). + * + * You can invoke [`removeReadStream()`](#removereadstream) to remove the + * read event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeReadStream() + */ + public function addReadStream($stream, $listener); + + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * Note that this low-level API is considered advanced usage. + * Most use cases should probably use the higher-level + * [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + * instead. + * + * The first parameter MUST be a valid stream resource that supports + * checking whether it is ready to write by this loop implementation. + * A single stream resource MUST NOT be added more than once. + * Instead, either call [`removeWriteStream()`](#removewritestream) first or + * react to this event with a single listener and then dispatch from this + * listener. This method MAY throw an `Exception` if the given resource type + * is not supported by this loop implementation. + * + * The second parameter MUST be a listener callback function that accepts + * the stream resource as its only parameter. + * If you don't use the stream resource inside your listener callback function + * you MAY use a function which has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * $loop->addWriteStream($stream, function ($stream) use ($name) { + * fwrite($stream, 'Hello ' . $name); + * }); + * ``` + * + * See also [example #12](examples). + * + * You can invoke [`removeWriteStream()`](#removewritestream) to remove the + * write event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * Some event loop implementations are known to only trigger the listener if + * the stream *becomes* readable (edge-triggered) and may not trigger if the + * stream has already been readable from the beginning. + * This also implies that a stream may not be recognized as readable when data + * is still left in PHP's internal stream buffers. + * As such, it's recommended to use `stream_set_read_buffer($stream, 0);` + * to disable PHP's internal read buffer in this case. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeWriteStream() + */ + public function addWriteStream($stream, $listener); + + /** + * Remove the read event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeReadStream($stream); + + /** + * Remove the write event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeWriteStream($stream); + + /** + * Enqueue a callback to be invoked once after the given interval. + * + * The second parameter MUST be a timer callback function that accepts + * the timer instance as its only parameter. + * If you don't use the timer instance inside your timer callback function + * you MAY use a function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * This method returns a timer instance. The same timer instance will also be + * passed into the timer callback function as described above. + * You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. + * Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure + * the callback will be invoked only once after the given interval. + * + * ```php + * $loop->addTimer(0.8, function () { + * echo 'world!' . PHP_EOL; + * }); + * + * $loop->addTimer(0.3, function () { + * echo 'hello '; + * }); + * ``` + * + * See also [example #1](examples). + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->addTimer(1.0, function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addTimer($interval, $callback); + + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * The second parameter MUST be a timer callback function that accepts + * the timer instance as its only parameter. + * If you don't use the timer instance inside your timer callback function + * you MAY use a function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * This method returns a timer instance. The same timer instance will also be + * passed into the timer callback function as described above. + * Unlike [`addTimer()`](#addtimer), this method will ensure the callback + * will be invoked infinitely after the given interval or until you invoke + * [`cancelTimer`](#canceltimer). + * + * ```php + * $timer = $loop->addPeriodicTimer(0.1, function () { + * echo 'tick!' . PHP_EOL; + * }); + * + * $loop->addTimer(1.0, function () use ($loop, $timer) { + * $loop->cancelTimer($timer); + * echo 'Done' . PHP_EOL; + * }); + * ``` + * + * See also [example #2](examples). + * + * If you want to limit the number of executions, you can bind + * arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $n = 3; + * $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + * if ($n > 0) { + * --$n; + * echo "hello $name\n"; + * } else { + * $loop->cancelTimer($timer); + * } + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * Additionally, periodic timers may be subject to timer drift due to + * re-scheduling after each invocation. As such, it's generally not + * recommended to rely on this for high precision intervals with millisecond + * accuracy or below. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addPeriodicTimer($interval, $callback); + + /** + * Cancel a pending timer. + * + * See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + * + * Calling this method on a timer instance that has not been added to this + * loop instance or on a timer that has already been cancelled has no effect. + * + * @param TimerInterface $timer The timer to cancel. + * + * @return void + */ + public function cancelTimer(TimerInterface $timer); + + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * This works very much similar to timers with an interval of zero seconds, + * but does not require the overhead of scheduling a timer queue. + * + * The tick callback function MUST be able to accept zero parameters. + * + * The tick callback function MUST NOT throw an `Exception`. + * The return value of the tick callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->futureTick(function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * Unlike timers, tick callbacks are guaranteed to be executed in the order + * they are enqueued. + * Also, once a callback is enqueued, there's no way to cancel this operation. + * + * This is often used to break down bigger tasks into smaller steps (a form + * of cooperative multitasking). + * + * ```php + * $loop->futureTick(function () { + * echo 'b'; + * }); + * $loop->futureTick(function () { + * echo 'c'; + * }); + * echo 'a'; + * ``` + * + * See also [example #3](examples). + * + * @param callable $listener The callback to invoke. + * + * @return void + */ + public function futureTick($listener); + + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * This is useful to catch user interrupt signals or shutdown signals from + * tools like `supervisor` or `systemd`. + * + * The second parameter MUST be a listener callback function that accepts + * the signal as its only parameter. + * If you don't use the signal inside your listener callback function + * you MAY use a function which has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * ```php + * $loop->addSignal(SIGINT, function (int $signal) { + * echo 'Caught user interrupt signal' . PHP_EOL; + * }); + * ``` + * + * See also [example #4](examples). + * + * Signaling is only available on Unix-like platforms, Windows isn't + * supported due to operating system limitations. + * This method may throw a `BadMethodCallException` if signals aren't + * supported on this platform, for example when required extensions are + * missing. + * + * **Note: A listener can only be added once to the same signal, any + * attempts to add it more than once will be ignored.** + * + * @param int $signal + * @param callable $listener + * + * @throws \BadMethodCallException when signals aren't supported on this + * platform, for example when required extensions are missing. + * + * @return void + */ + public function addSignal($signal, $listener); + + /** + * Removes a previously added signal listener. + * + * ```php + * $loop->removeSignal(SIGINT, $listener); + * ``` + * + * Any attempts to remove listeners that aren't registered will be ignored. + * + * @param int $signal + * @param callable $listener + * + * @return void + */ + public function removeSignal($signal, $listener); + + /** + * Run the event loop until there are no more tasks to perform. + * + * For many applications, this method is the only directly visible + * invocation on the event loop. + * As a rule of thumb, it is usually recommended to attach everything to the + * same loop instance and then run the loop once at the bottom end of the + * application. + * + * ```php + * $loop->run(); + * ``` + * + * This method will keep the loop running until there are no more tasks + * to perform. In other words: This method will block until the last + * timer, stream and/or signal has been removed. + * + * Likewise, it is imperative to ensure the application actually invokes + * this method once. Adding listeners to the loop and missing to actually + * run it will result in the application exiting without actually waiting + * for any of the attached listeners. + * + * This method MUST NOT be called while the loop is already running. + * This method MAY be called more than once after it has explicitly been + * [`stop()`ped](#stop) or after it automatically stopped because it + * previously did no longer have anything to do. + * + * @return void + */ + public function run(); + + /** + * Instruct a running event loop to stop. + * + * This method is considered advanced usage and should be used with care. + * As a rule of thumb, it is usually recommended to let the loop stop + * only automatically when it no longer has anything to do. + * + * This method can be used to explicitly instruct the event loop to stop: + * + * ```php + * $loop->addTimer(3.0, function () use ($loop) { + * $loop->stop(); + * }); + * ``` + * + * Calling this method on a loop instance that is not currently running or + * on a loop instance that has already been stopped has no effect. + * + * @return void + */ + public function stop(); +} diff --git a/trilhas_poo/vendor/react/event-loop/src/SignalsHandler.php b/trilhas_poo/vendor/react/event-loop/src/SignalsHandler.php new file mode 100644 index 0000000..10d125d --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/SignalsHandler.php @@ -0,0 +1,63 @@ +signals[$signal])) { + $this->signals[$signal] = array(); + } + + if (\in_array($listener, $this->signals[$signal])) { + return; + } + + $this->signals[$signal][] = $listener; + } + + public function remove($signal, $listener) + { + if (!isset($this->signals[$signal])) { + return; + } + + $index = \array_search($listener, $this->signals[$signal], true); + unset($this->signals[$signal][$index]); + + if (isset($this->signals[$signal]) && \count($this->signals[$signal]) === 0) { + unset($this->signals[$signal]); + } + } + + public function call($signal) + { + if (!isset($this->signals[$signal])) { + return; + } + + foreach ($this->signals[$signal] as $listener) { + \call_user_func($listener, $signal); + } + } + + public function count($signal) + { + if (!isset($this->signals[$signal])) { + return 0; + } + + return \count($this->signals[$signal]); + } + + public function isEmpty() + { + return !$this->signals; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/StreamSelectLoop.php b/trilhas_poo/vendor/react/event-loop/src/StreamSelectLoop.php new file mode 100644 index 0000000..1686fd7 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/StreamSelectLoop.php @@ -0,0 +1,330 @@ +futureTickQueue = new FutureTickQueue(); + $this->timers = new Timers(); + $this->pcntl = \function_exists('pcntl_signal') && \function_exists('pcntl_signal_dispatch'); + $this->pcntlPoll = $this->pcntl && !\function_exists('pcntl_async_signals'); + $this->signals = new SignalsHandler(); + + // prefer async signals if available (PHP 7.1+) or fall back to dispatching on each tick + if ($this->pcntl && !$this->pcntlPoll) { + \pcntl_async_signals(true); + } + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + + if (!isset($this->readStreams[$key])) { + $this->readStreams[$key] = $stream; + $this->readListeners[$key] = $listener; + } + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + + if (!isset($this->writeStreams[$key])) { + $this->writeStreams[$key] = $stream; + $this->writeListeners[$key] = $listener; + } + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + unset( + $this->readStreams[$key], + $this->readListeners[$key] + ); + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + unset( + $this->writeStreams[$key], + $this->writeListeners[$key] + ); + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->timers->add($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->timers->add($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + $this->timers->cancel($timer); + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + if ($this->pcntl === false) { + throw new \BadMethodCallException('Event loop feature "signals" isn\'t supported by the "StreamSelectLoop"'); + } + + $first = $this->signals->count($signal) === 0; + $this->signals->add($signal, $listener); + + if ($first) { + \pcntl_signal($signal, array($this->signals, 'call')); + } + } + + public function removeSignal($signal, $listener) + { + if (!$this->signals->count($signal)) { + return; + } + + $this->signals->remove($signal, $listener); + + if ($this->signals->count($signal) === 0) { + \pcntl_signal($signal, \SIG_DFL); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $this->timers->tick(); + + // Future-tick queue has pending callbacks ... + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $timeout = 0; + + // There is a pending timer, only block until it is due ... + } elseif ($scheduledAt = $this->timers->getFirst()) { + $timeout = $scheduledAt - $this->timers->getTime(); + if ($timeout < 0) { + $timeout = 0; + } else { + // Convert float seconds to int microseconds. + // Ensure we do not exceed maximum integer size, which may + // cause the loop to tick once every ~35min on 32bit systems. + $timeout *= self::MICROSECONDS_PER_SECOND; + $timeout = $timeout > \PHP_INT_MAX ? \PHP_INT_MAX : (int)$timeout; + } + + // The only possible event is stream or signal activity, so wait forever ... + } elseif ($this->readStreams || $this->writeStreams || !$this->signals->isEmpty()) { + $timeout = null; + + // There's nothing left to do ... + } else { + break; + } + + $this->waitForStreamActivity($timeout); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Wait/check for stream activity, or until the next timer is due. + * + * @param integer|null $timeout Activity timeout in microseconds, or null to wait forever. + */ + private function waitForStreamActivity($timeout) + { + $read = $this->readStreams; + $write = $this->writeStreams; + + $available = $this->streamSelect($read, $write, $timeout); + if ($this->pcntlPoll) { + \pcntl_signal_dispatch(); + } + if (false === $available) { + // if a system call has been interrupted, + // we cannot rely on it's outcome + return; + } + + foreach ($read as $stream) { + $key = (int) $stream; + + if (isset($this->readListeners[$key])) { + \call_user_func($this->readListeners[$key], $stream); + } + } + + foreach ($write as $stream) { + $key = (int) $stream; + + if (isset($this->writeListeners[$key])) { + \call_user_func($this->writeListeners[$key], $stream); + } + } + } + + /** + * Emulate a stream_select() implementation that does not break when passed + * empty stream arrays. + * + * @param array $read An array of read streams to select upon. + * @param array $write An array of write streams to select upon. + * @param int|null $timeout Activity timeout in microseconds, or null to wait forever. + * + * @return int|false The total number of streams that are ready for read/write. + * Can return false if stream_select() is interrupted by a signal. + */ + private function streamSelect(array &$read, array &$write, $timeout) + { + if ($read || $write) { + // We do not usually use or expose the `exceptfds` parameter passed to the underlying `select`. + // However, Windows does not report failed connection attempts in `writefds` passed to `select` like most other platforms. + // Instead, it uses `writefds` only for successful connection attempts and `exceptfds` for failed connection attempts. + // We work around this by adding all sockets that look like a pending connection attempt to `exceptfds` automatically on Windows and merge it back later. + // This ensures the public API matches other loop implementations across all platforms (see also test suite or rather test matrix). + // Lacking better APIs, every write-only socket that has not yet read any data is assumed to be in a pending connection attempt state. + // @link https://docs.microsoft.com/de-de/windows/win32/api/winsock2/nf-winsock2-select + $except = null; + if (\DIRECTORY_SEPARATOR === '\\') { + $except = array(); + foreach ($write as $key => $socket) { + if (!isset($read[$key]) && @\ftell($socket) === 0) { + $except[$key] = $socket; + } + } + } + + /** @var ?callable $previous */ + $previous = \set_error_handler(function ($errno, $errstr) use (&$previous) { + // suppress warnings that occur when `stream_select()` is interrupted by a signal + // PHP defines `EINTR` through `ext-sockets` or `ext-pcntl`, otherwise use common default (Linux & Mac) + $eintr = \defined('SOCKET_EINTR') ? \SOCKET_EINTR : (\defined('PCNTL_EINTR') ? \PCNTL_EINTR : 4); + if ($errno === \E_WARNING && \strpos($errstr, '[' . $eintr .']: ') !== false) { + return; + } + + // forward any other error to registered error handler or print warning + return ($previous !== null) ? \call_user_func_array($previous, \func_get_args()) : false; + }); + + try { + $ret = \stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout); + \restore_error_handler(); + } catch (\Throwable $e) { // @codeCoverageIgnoreStart + \restore_error_handler(); + throw $e; + } catch (\Exception $e) { + \restore_error_handler(); + throw $e; + } // @codeCoverageIgnoreEnd + + if ($except) { + $write = \array_merge($write, $except); + } + return $ret; + } + + if ($timeout > 0) { + \usleep($timeout); + } elseif ($timeout === null) { + // wait forever (we only reach this if we're only awaiting signals) + // this may be interrupted and return earlier when a signal is received + \sleep(PHP_INT_MAX); + } + + return 0; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/Tick/FutureTickQueue.php b/trilhas_poo/vendor/react/event-loop/src/Tick/FutureTickQueue.php new file mode 100644 index 0000000..efabcbc --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/Tick/FutureTickQueue.php @@ -0,0 +1,60 @@ +queue = new SplQueue(); + } + + /** + * Add a callback to be invoked on a future tick of the event loop. + * + * Callbacks are guaranteed to be executed in the order they are enqueued. + * + * @param callable $listener The callback to invoke. + */ + public function add($listener) + { + $this->queue->enqueue($listener); + } + + /** + * Flush the callback queue. + */ + public function tick() + { + // Only invoke as many callbacks as were on the queue when tick() was called. + $count = $this->queue->count(); + + while ($count--) { + \call_user_func( + $this->queue->dequeue() + ); + } + } + + /** + * Check if the next tick queue is empty. + * + * @return boolean + */ + public function isEmpty() + { + return $this->queue->isEmpty(); + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/Timer/Timer.php b/trilhas_poo/vendor/react/event-loop/src/Timer/Timer.php new file mode 100644 index 0000000..da3602a --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/Timer/Timer.php @@ -0,0 +1,55 @@ +interval = (float) $interval; + $this->callback = $callback; + $this->periodic = (bool) $periodic; + } + + public function getInterval() + { + return $this->interval; + } + + public function getCallback() + { + return $this->callback; + } + + public function isPeriodic() + { + return $this->periodic; + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/Timer/Timers.php b/trilhas_poo/vendor/react/event-loop/src/Timer/Timers.php new file mode 100644 index 0000000..53c46d0 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/Timer/Timers.php @@ -0,0 +1,113 @@ +useHighResolution = \function_exists('hrtime'); + } + + public function updateTime() + { + return $this->time = $this->useHighResolution ? \hrtime(true) * 1e-9 : \microtime(true); + } + + public function getTime() + { + return $this->time ?: $this->updateTime(); + } + + public function add(TimerInterface $timer) + { + $id = \PHP_VERSION_ID < 70200 ? \spl_object_hash($timer) : \spl_object_id($timer); + $this->timers[$id] = $timer; + $this->schedule[$id] = $timer->getInterval() + $this->updateTime(); + $this->sorted = false; + } + + public function contains(TimerInterface $timer) + { + $id = \PHP_VERSION_ID < 70200 ? \spl_object_hash($timer) : \spl_object_id($timer); + return isset($this->timers[$id]); + } + + public function cancel(TimerInterface $timer) + { + $id = \PHP_VERSION_ID < 70200 ? \spl_object_hash($timer) : \spl_object_id($timer); + unset($this->timers[$id], $this->schedule[$id]); + } + + public function getFirst() + { + // ensure timers are sorted to simply accessing next (first) one + if (!$this->sorted) { + $this->sorted = true; + \asort($this->schedule); + } + + return \reset($this->schedule); + } + + public function isEmpty() + { + return \count($this->timers) === 0; + } + + public function tick() + { + // hot path: skip timers if nothing is scheduled + if (!$this->schedule) { + return; + } + + // ensure timers are sorted so we can execute in order + if (!$this->sorted) { + $this->sorted = true; + \asort($this->schedule); + } + + $time = $this->updateTime(); + + foreach ($this->schedule as $id => $scheduled) { + // schedule is ordered, so loop until first timer that is not scheduled for execution now + if ($scheduled >= $time) { + break; + } + + // skip any timers that are removed while we process the current schedule + if (!isset($this->schedule[$id]) || $this->schedule[$id] !== $scheduled) { + continue; + } + + $timer = $this->timers[$id]; + \call_user_func($timer->getCallback(), $timer); + + // re-schedule if this is a periodic timer and it has not been cancelled explicitly already + if ($timer->isPeriodic() && isset($this->timers[$id])) { + $this->schedule[$id] = $timer->getInterval() + $time; + $this->sorted = false; + } else { + unset($this->timers[$id], $this->schedule[$id]); + } + } + } +} diff --git a/trilhas_poo/vendor/react/event-loop/src/TimerInterface.php b/trilhas_poo/vendor/react/event-loop/src/TimerInterface.php new file mode 100644 index 0000000..cdcf773 --- /dev/null +++ b/trilhas_poo/vendor/react/event-loop/src/TimerInterface.php @@ -0,0 +1,27 @@ +` and `reject(Throwable $reason): PromiseInterface`. + It is no longer possible to resolve a promise without a value (use `null` instead) or reject a promise without a reason (use `Throwable` instead). + (#93, #141 and #142 by @jsor, #138, #149 and #247 by @WyriHaximus and #213 and #246 by @clue) + + ```php + // old (arguments used to be optional) + $promise = resolve(); + $promise = reject(); + + // new (already supported before) + $promise = resolve(null); + $promise = reject(new RuntimeException()); + ``` + +* Feature / BC break: Report all unhandled rejections by default and remove ~~`done()`~~ method. + Add new `set_rejection_handler()` function to set the global rejection handler for unhandled promise rejections. + (#248, #249 and #224 by @clue) + + ```php + // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 + reject(new RuntimeException('Unhandled')); + ``` + +* BC break: Remove all deprecated APIs and reduce API surface. + Remove ~~`some()`~~, ~~`map()`~~, ~~`reduce()`~~ functions, use `any()` and `all()` functions instead. + Remove internal ~~`FulfilledPromise`~~ and ~~`RejectedPromise`~~ classes, use `resolve()` and `reject()` functions instead. + Remove legacy promise progress API (deprecated third argument to `then()` method) and deprecated ~~`LazyPromise`~~ class. + (#32 and #98 by @jsor and #164, #219 and #220 by @clue) + +* BC break: Make all classes final to encourage composition over inheritance. + (#80 by @jsor) + +* Feature / BC break: Require `array` (or `iterable`) type for `all()` + `race()` + `any()` functions and bring in line with ES6 specification. + These functions now require a single argument with a variable number of promises or values as input. + (#225 by @clue and #35 by @jsor) + +* Fix / BC break: Fix `race()` to return a forever pending promise when called with an empty `array` (or `iterable`) and bring in line with ES6 specification. + (#83 by @jsor and #225 by @clue) + +* Minor performance improvements by initializing `Deferred` in the constructor and avoiding `call_user_func()` calls. + (#151 by @WyriHaximus and #171 by @Kubo2) + +* Minor documentation improvements. + (#110 by @seregazhuk, #132 by @CharlotteDunois, #145 by @danielecr, #178 by @WyriHaximus, #189 by @srdante, #212 by @clue, #214, #239 and #243 by @SimonFrings and #231 by @nhedger) + +The following changes had to be ported to this release due to our branching +strategy, but also appeared in the [`2.x` branch](https://github.com/reactphp/promise/tree/2.x): + +* Feature: Support union types and address deprecation of `ReflectionType::getClass()` (PHP 8+). + (#197 by @cdosoftei and @SimonFrings) + +* Feature: Support intersection types (PHP 8.1+). + (#209 by @bzikarsky) + +* Feature: Support DNS types (PHP 8.2+). + (#236 by @nhedger) + +* Feature: Port all memory improvements from `2.x` to `3.x`. + (#150 by @clue and @WyriHaximus) + +* Fix: Fix checking whether cancellable promise is an object and avoid possible warning. + (#161 by @smscr) + +* Improve performance by prefixing all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#134 by @WyriHaximus) + +* Improve test suite, update PHPUnit and PHP versions and add `.gitattributes` to exclude dev files from exports. + (#107 by @carusogabriel, #148 and #234 by @WyriHaximus, #153 by @reedy, #162, #230 and #240 by @clue, #173, #177, #185 and #199 by @SimonFrings, #193 by @woodongwong and #210 by @bzikarsky) + +The following changes were originally planned for this release but later reverted +and are not part of the final release: + +* Add iterative callback queue handler to avoid recursion (later removed to improve Fiber support). + (#28, #82 and #86 by @jsor, #158 by @WyriHaximus and #229 and #238 by @clue) + +* Trigger an `E_USER_ERROR` instead of throwing an exception from `done()` (later removed entire `done()` method to globally report unhandled rejections). + (#97 by @jsor and #224 and #248 by @clue) + +* Add type declarations for `some()` (later removed entire `some()` function). + (#172 by @WyriHaximus and #219 by @clue) + +## 2.0.0 (2013-12-10) + +See [`2.x` CHANGELOG](https://github.com/reactphp/promise/blob/2.x/CHANGELOG.md) for more details. + +## 1.0.0 (2012-11-07) + +See [`1.x` CHANGELOG](https://github.com/reactphp/promise/blob/1.x/CHANGELOG.md) for more details. diff --git a/trilhas_poo/vendor/react/promise/LICENSE b/trilhas_poo/vendor/react/promise/LICENSE new file mode 100644 index 0000000..21c1357 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2012 Jan Sorgalla, Christian Lück, Cees-Jan Kiewiet, Chris Boden + +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/trilhas_poo/vendor/react/promise/README.md b/trilhas_poo/vendor/react/promise/README.md new file mode 100644 index 0000000..2108d98 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/README.md @@ -0,0 +1,722 @@ +Promise +======= + +A lightweight implementation of +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +[![CI status](https://github.com/reactphp/promise/workflows/CI/badge.svg)](https://github.com/reactphp/promise/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/promise?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/promise) + +Table of Contents +----------------- + +1. [Introduction](#introduction) +2. [Concepts](#concepts) + * [Deferred](#deferred) + * [Promise](#promise-1) +3. [API](#api) + * [Deferred](#deferred-1) + * [Deferred::promise()](#deferredpromise) + * [Deferred::resolve()](#deferredresolve) + * [Deferred::reject()](#deferredreject) + * [PromiseInterface](#promiseinterface) + * [PromiseInterface::then()](#promiseinterfacethen) + * [PromiseInterface::catch()](#promiseinterfacecatch) + * [PromiseInterface::finally()](#promiseinterfacefinally) + * [PromiseInterface::cancel()](#promiseinterfacecancel) + * [~~PromiseInterface::otherwise()~~](#promiseinterfaceotherwise) + * [~~PromiseInterface::always()~~](#promiseinterfacealways) + * [Promise](#promise-2) + * [Functions](#functions) + * [resolve()](#resolve) + * [reject()](#reject) + * [all()](#all) + * [race()](#race) + * [any()](#any) + * [set_rejection_handler()](#set_rejection_handler) +4. [Examples](#examples) + * [How to use Deferred](#how-to-use-deferred) + * [How promise forwarding works](#how-promise-forwarding-works) + * [Resolution forwarding](#resolution-forwarding) + * [Rejection forwarding](#rejection-forwarding) + * [Mixed resolution and rejection forwarding](#mixed-resolution-and-rejection-forwarding) +5. [Install](#install) +6. [Tests](#tests) +7. [Credits](#credits) +8. [License](#license) + +Introduction +------------ + +Promise is a library implementing +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +It also provides several other useful promise-related concepts, such as joining +multiple promises and mapping and reducing collections of promises. + +If you've never heard about promises before, +[read this first](https://gist.github.com/domenic/3889970). + +Concepts +-------- + +### Deferred + +A **Deferred** represents a computation or unit of work that may not have +completed yet. Typically (but not always), that computation will be something +that executes asynchronously and completes at some point in the future. + +### Promise + +While a deferred represents the computation itself, a **Promise** represents +the result of that computation. Thus, each deferred has a promise that acts as +a placeholder for its actual result. + +API +--- + +### Deferred + +A deferred represents an operation whose resolution is pending. It has separate +promise and resolver parts. + +```php +$deferred = new React\Promise\Deferred(); + +$promise = $deferred->promise(); + +$deferred->resolve(mixed $value); +$deferred->reject(\Throwable $reason); +``` + +The `promise` method returns the promise of the deferred. + +The `resolve` and `reject` methods control the state of the deferred. + +The constructor of the `Deferred` accepts an optional `$canceller` argument. +See [Promise](#promise-2) for more information. + +#### Deferred::promise() + +```php +$promise = $deferred->promise(); +``` + +Returns the promise of the deferred, which you can hand out to others while +keeping the authority to modify its state to yourself. + +#### Deferred::resolve() + +```php +$deferred->resolve(mixed $value); +``` + +Resolves the promise returned by `promise()`. All consumers are notified by +having `$onFulfilled` (which they registered via `$promise->then()`) called with +`$value`. + +If `$value` itself is a promise, the promise will transition to the state of +this promise once it is resolved. + +See also the [`resolve()` function](#resolve). + +#### Deferred::reject() + +```php +$deferred->reject(\Throwable $reason); +``` + +Rejects the promise returned by `promise()`, signalling that the deferred's +computation failed. +All consumers are notified by having `$onRejected` (which they registered via +`$promise->then()`) called with `$reason`. + +See also the [`reject()` function](#reject). + +### PromiseInterface + +The promise interface provides the common interface for all promise +implementations. +See [Promise](#promise-2) for the only public implementation exposed by this +package. + +A promise represents an eventual outcome, which is either fulfillment (success) +and an associated value, or rejection (failure) and an associated reason. + +Once in the fulfilled or rejected state, a promise becomes immutable. +Neither its state nor its result (or error) can be modified. + +#### PromiseInterface::then() + +```php +$transformedPromise = $promise->then(callable $onFulfilled = null, callable $onRejected = null); +``` + +Transforms a promise's value by applying a function to the promise's fulfillment +or rejection value. Returns a new promise for the transformed result. + +The `then()` method registers new fulfilled and rejection handlers with a promise +(all parameters are optional): + + * `$onFulfilled` will be invoked once the promise is fulfilled and passed + the result as the first argument. + * `$onRejected` will be invoked once the promise is rejected and passed the + reason as the first argument. + +It returns a new promise that will fulfill with the return value of either +`$onFulfilled` or `$onRejected`, whichever is called, or will reject with +the thrown exception if either throws. + +A promise makes the following guarantees about handlers registered in +the same call to `then()`: + + 1. Only one of `$onFulfilled` or `$onRejected` will be called, + never both. + 2. `$onFulfilled` and `$onRejected` will never be called more + than once. + +#### See also + +* [resolve()](#resolve) - Creating a resolved promise +* [reject()](#reject) - Creating a rejected promise + +#### PromiseInterface::catch() + +```php +$promise->catch(callable $onRejected); +``` + +Registers a rejection handler for promise. It is a shortcut for: + +```php +$promise->then(null, $onRejected); +``` + +Additionally, you can type hint the `$reason` argument of `$onRejected` to catch +only specific errors. + +```php +$promise + ->catch(function (\RuntimeException $reason) { + // Only catch \RuntimeException instances + // All other types of errors will propagate automatically + }) + ->catch(function (\Throwable $reason) { + // Catch other errors + }); +``` + +#### PromiseInterface::finally() + +```php +$newPromise = $promise->finally(callable $onFulfilledOrRejected); +``` + +Allows you to execute "cleanup" type tasks in a promise chain. + +It arranges for `$onFulfilledOrRejected` to be called, with no arguments, +when the promise is either fulfilled or rejected. + +* If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will fulfill with the same value as `$promise`. +* If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. +* If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will reject with the same reason as `$promise`. +* If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. + +`finally()` behaves similarly to the synchronous finally statement. When combined +with `catch()`, `finally()` allows you to write code that is similar to the familiar +synchronous catch/finally pair. + +Consider the following synchronous code: + +```php +try { + return doSomething(); +} catch (\Throwable $e) { + return handleError($e); +} finally { + cleanup(); +} +``` + +Similar asynchronous code (with `doSomething()` that returns a promise) can be +written: + +```php +return doSomething() + ->catch('handleError') + ->finally('cleanup'); +``` + +#### PromiseInterface::cancel() + +``` php +$promise->cancel(); +``` + +The `cancel()` method notifies the creator of the promise that there is no +further interest in the results of the operation. + +Once a promise is settled (either fulfilled or rejected), calling `cancel()` on +a promise has no effect. + +#### ~~PromiseInterface::otherwise()~~ + +> Deprecated since v3.0.0, see [`catch()`](#promiseinterfacecatch) instead. + +The `otherwise()` method registers a rejection handler for a promise. + +This method continues to exist only for BC reasons and to ease upgrading +between versions. It is an alias for: + +```php +$promise->catch($onRejected); +``` + +#### ~~PromiseInterface::always()~~ + +> Deprecated since v3.0.0, see [`finally()`](#promiseinterfacefinally) instead. + +The `always()` method allows you to execute "cleanup" type tasks in a promise chain. + +This method continues to exist only for BC reasons and to ease upgrading +between versions. It is an alias for: + +```php +$promise->finally($onFulfilledOrRejected); +``` + +### Promise + +Creates a promise whose state is controlled by the functions passed to +`$resolver`. + +```php +$resolver = function (callable $resolve, callable $reject) { + // Do some work, possibly asynchronously, and then + // resolve or reject. + + $resolve($awesomeResult); + // or throw new Exception('Promise rejected'); + // or $resolve($anotherPromise); + // or $reject($nastyError); +}; + +$canceller = function () { + // Cancel/abort any running operations like network connections, streams etc. + + // Reject promise by throwing an exception + throw new Exception('Promise cancelled'); +}; + +$promise = new React\Promise\Promise($resolver, $canceller); +``` + +The promise constructor receives a resolver function and an optional canceller +function which both will be called with two arguments: + + * `$resolve($value)` - Primary function that seals the fate of the + returned promise. Accepts either a non-promise value, or another promise. + When called with a non-promise value, fulfills promise with that value. + When called with another promise, e.g. `$resolve($otherPromise)`, promise's + fate will be equivalent to that of `$otherPromise`. + * `$reject($reason)` - Function that rejects the promise. It is recommended to + just throw an exception instead of using `$reject()`. + +If the resolver or canceller throw an exception, the promise will be rejected +with that thrown exception as the rejection reason. + +The resolver function will be called immediately, the canceller function only +once all consumers called the `cancel()` method of the promise. + +### Functions + +Useful functions for creating and joining collections of promises. + +All functions working on promise collections (like `all()`, `race()`, +etc.) support cancellation. This means, if you call `cancel()` on the returned +promise, all promises in the collection are cancelled. + +#### resolve() + +```php +$promise = React\Promise\resolve(mixed $promiseOrValue); +``` + +Creates a promise for the supplied `$promiseOrValue`. + +If `$promiseOrValue` is a value, it will be the resolution value of the +returned promise. + +If `$promiseOrValue` is a thenable (any object that provides a `then()` method), +a trusted promise that follows the state of the thenable is returned. + +If `$promiseOrValue` is a promise, it will be returned as is. + +The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) +and can be consumed like any other promise: + +```php +$promise = React\Promise\resolve(42); + +$promise->then(function (int $result): void { + var_dump($result); +}, function (\Throwable $e): void { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +#### reject() + +```php +$promise = React\Promise\reject(\Throwable $reason); +``` + +Creates a rejected promise for the supplied `$reason`. + +Note that the [`\Throwable`](https://www.php.net/manual/en/class.throwable.php) interface introduced in PHP 7 covers +both user land [`\Exception`](https://www.php.net/manual/en/class.exception.php)'s and +[`\Error`](https://www.php.net/manual/en/class.error.php) internal PHP errors. By enforcing `\Throwable` as reason to +reject a promise, any language error or user land exception can be used to reject a promise. + +The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) +and can be consumed like any other promise: + +```php +$promise = React\Promise\reject(new RuntimeException('Request failed')); + +$promise->then(function (int $result): void { + var_dump($result); +}, function (\Throwable $e): void { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that rejected promises should always be handled similar to how any +exceptions should always be caught in a `try` + `catch` block. If you remove the +last reference to a rejected promise that has not been handled, it will +report an unhandled promise rejection: + +```php +function incorrect(): int +{ + $promise = React\Promise\reject(new RuntimeException('Request failed')); + + // Commented out: No rejection handler registered here. + // $promise->then(null, function (\Throwable $e): void { /* ignore */ }); + + // Returning from a function will remove all local variable references, hence why + // this will report an unhandled promise rejection here. + return 42; +} + +// Calling this function will log an error message plus its stack trace: +// Unhandled promise rejection with RuntimeException: Request failed in example.php:10 +incorrect(); +``` + +A rejected promise will be considered "handled" if you catch the rejection +reason with either the [`then()` method](#promiseinterfacethen), the +[`catch()` method](#promiseinterfacecatch), or the +[`finally()` method](#promiseinterfacefinally). Note that each of these methods +return a new promise that may again be rejected if you re-throw an exception. + +A rejected promise will also be considered "handled" if you abort the operation +with the [`cancel()` method](#promiseinterfacecancel) (which in turn would +usually reject the promise if it is still pending). + +See also the [`set_rejection_handler()` function](#set_rejection_handler). + +#### all() + +```php +$promise = React\Promise\all(iterable $promisesOrValues); +``` + +Returns a promise that will resolve only once all the items in +`$promisesOrValues` have resolved. The resolution value of the returned promise +will be an array containing the resolution values of each of the items in +`$promisesOrValues`. + +#### race() + +```php +$promise = React\Promise\race(iterable $promisesOrValues); +``` + +Initiates a competitive race that allows one winner. Returns a promise which is +resolved in the same way the first settled promise resolves. + +The returned promise will become **infinitely pending** if `$promisesOrValues` +contains 0 items. + +#### any() + +```php +$promise = React\Promise\any(iterable $promisesOrValues); +``` + +Returns a promise that will resolve when any one of the items in +`$promisesOrValues` resolves. The resolution value of the returned promise +will be the resolution value of the triggering item. + +The returned promise will only reject if *all* items in `$promisesOrValues` are +rejected. The rejection value will be a `React\Promise\Exception\CompositeException` +which holds all rejection reasons. The rejection reasons can be obtained with +`CompositeException::getThrowables()`. + +The returned promise will also reject with a `React\Promise\Exception\LengthException` +if `$promisesOrValues` contains 0 items. + +#### set_rejection_handler() + +```php +React\Promise\set_rejection_handler(?callable $callback): ?callable; +``` + +Sets the global rejection handler for unhandled promise rejections. + +Note that rejected promises should always be handled similar to how any +exceptions should always be caught in a `try` + `catch` block. If you remove +the last reference to a rejected promise that has not been handled, it will +report an unhandled promise rejection. See also the [`reject()` function](#reject) +for more details. + +The `?callable $callback` argument MUST be a valid callback function that +accepts a single `Throwable` argument or a `null` value to restore the +default promise rejection handler. The return value of the callback function +will be ignored and has no effect, so you SHOULD return a `void` value. The +callback function MUST NOT throw or the program will be terminated with a +fatal error. + +The function returns the previous rejection handler or `null` if using the +default promise rejection handler. + +The default promise rejection handler will log an error message plus its stack +trace: + +```php +// Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 +React\Promise\reject(new RuntimeException('Unhandled')); +``` + +The promise rejection handler may be used to use customize the log message or +write to custom log targets. As a rule of thumb, this function should only be +used as a last resort and promise rejections are best handled with either the +[`then()` method](#promiseinterfacethen), the +[`catch()` method](#promiseinterfacecatch), or the +[`finally()` method](#promiseinterfacefinally). +See also the [`reject()` function](#reject) for more details. + +Examples +-------- + +### How to use Deferred + +```php +function getAwesomeResultPromise() +{ + $deferred = new React\Promise\Deferred(); + + // Execute a Node.js-style function using the callback pattern + computeAwesomeResultAsynchronously(function (\Throwable $error, $result) use ($deferred) { + if ($error) { + $deferred->reject($error); + } else { + $deferred->resolve($result); + } + }); + + // Return the promise + return $deferred->promise(); +} + +getAwesomeResultPromise() + ->then( + function ($value) { + // Deferred resolved, do something with $value + }, + function (\Throwable $reason) { + // Deferred rejected, do something with $reason + } + ); +``` + +### How promise forwarding works + +A few simple examples to show how the mechanics of Promises/A forwarding works. +These examples are contrived, of course, and in real usage, promise chains will +typically be spread across several function calls, or even several levels of +your application architecture. + +#### Resolution forwarding + +Resolved promises forward resolution values to the next promise. +The first promise, `$deferred->promise()`, will resolve with the value passed +to `$deferred->resolve()` below. + +Each call to `then()` returns a new promise that will resolve with the return +value of the previous handler. This creates a promise "pipeline". + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + // $x will be the value passed to $deferred->resolve() below + // and returns a *new promise* for $x + 1 + return $x + 1; + }) + ->then(function ($x) { + // $x === 2 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 3 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 4 + // This handler receives the return value of the + // previous handler. + echo 'Resolve ' . $x; + }); + +$deferred->resolve(1); // Prints "Resolve 4" +``` + +#### Rejection forwarding + +Rejected promises behave similarly, and also work similarly to try/catch: +When you catch an exception, you must rethrow for it to propagate. + +Similarly, when you handle a rejected promise, to propagate the rejection, +"rethrow" it by either returning a rejected promise, or actually throwing +(since promise translates thrown exceptions into rejections) + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->catch(function (\Exception $x) { + // Propagate the rejection + throw $x; + }) + ->catch(function (\Exception $x) { + // Can also propagate by returning another rejection + return React\Promise\reject( + new \Exception($x->getMessage() + 1) + ); + }) + ->catch(function ($x) { + echo 'Reject ' . $x->getMessage(); // 3 + }); + +$deferred->resolve(1); // Prints "Reject 3" +``` + +#### Mixed resolution and rejection forwarding + +Just like try/catch, you can choose to propagate or not. Mixing resolutions and +rejections will still forward handler results in a predictable way. + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + return $x + 1; + }) + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->catch(function (\Exception $x) { + // Handle the rejection, and don't propagate. + // This is like catch without a rethrow + return $x->getMessage() + 1; + }) + ->then(function ($x) { + echo 'Mixed ' . $x; // 4 + }); + +$deferred->resolve(1); // Prints "Mixed 4" +``` + +Install +------- + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version from this branch: + +```bash +composer require react/promise:^3.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on PHP 7.1 through current PHP 8+. +It's *highly recommended to use the latest supported PHP version* for this project. + +We're committed to providing long-term support (LTS) options and to provide a +smooth upgrade path. If you're using an older PHP version, you may use the +[`2.x` branch](https://github.com/reactphp/promise/tree/2.x) (PHP 5.4+) or +[`1.x` branch](https://github.com/reactphp/promise/tree/1.x) (PHP 5.3+) which both +provide a compatible API but do not take advantage of newer language features. +You may target multiple versions at the same time to support a wider range of +PHP versions like this: + +```bash +composer require "react/promise:^3 || ^2 || ^1" +``` + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +On top of this, we use PHPStan on max level to ensure type safety across the project: + +```bash +vendor/bin/phpstan +``` + +Credits +------- + +Promise is a port of [when.js](https://github.com/cujojs/when) +by [Brian Cavalier](https://github.com/briancavalier). + +Also, large parts of the documentation have been ported from the when.js +[Wiki](https://github.com/cujojs/when/wiki) and the +[API docs](https://github.com/cujojs/when/blob/master/docs/api.md). + +License +------- + +Released under the [MIT](LICENSE) license. diff --git a/trilhas_poo/vendor/react/promise/composer.json b/trilhas_poo/vendor/react/promise/composer.json new file mode 100644 index 0000000..6bf687d --- /dev/null +++ b/trilhas_poo/vendor/react/promise/composer.json @@ -0,0 +1,57 @@ +{ + "name": "react/promise", + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "license": "MIT", + "authors": [ + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan/phpstan": "1.12.28 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^7.5" + }, + "autoload": { + "psr-4": { + "React\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "React\\Promise\\": [ + "tests/fixtures/", + "tests/" + ] + }, + "files": [ + "tests/Fiber.php" + ] + }, + "keywords": [ + "promise", + "promises" + ] +} diff --git a/trilhas_poo/vendor/react/promise/src/Deferred.php b/trilhas_poo/vendor/react/promise/src/Deferred.php new file mode 100644 index 0000000..80b8fcf --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Deferred.php @@ -0,0 +1,52 @@ + + */ + private $promise; + + /** @var callable(T):void */ + private $resolveCallback; + + /** @var callable(\Throwable):void */ + private $rejectCallback; + + /** + * @param (callable(callable(T):void,callable(\Throwable):void):void)|null $canceller + */ + public function __construct(?callable $canceller = null) + { + $this->promise = new Promise(function ($resolve, $reject): void { + $this->resolveCallback = $resolve; + $this->rejectCallback = $reject; + }, $canceller); + } + + /** + * @return PromiseInterface + */ + public function promise(): PromiseInterface + { + return $this->promise; + } + + /** + * @param T $value + */ + public function resolve($value): void + { + ($this->resolveCallback)($value); + } + + public function reject(\Throwable $reason): void + { + ($this->rejectCallback)($reason); + } +} diff --git a/trilhas_poo/vendor/react/promise/src/Exception/CompositeException.php b/trilhas_poo/vendor/react/promise/src/Exception/CompositeException.php new file mode 100644 index 0000000..2e672a0 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Exception/CompositeException.php @@ -0,0 +1,32 @@ +throwables = $throwables; + } + + /** + * @return \Throwable[] + */ + public function getThrowables(): array + { + return $this->throwables; + } +} diff --git a/trilhas_poo/vendor/react/promise/src/Exception/LengthException.php b/trilhas_poo/vendor/react/promise/src/Exception/LengthException.php new file mode 100644 index 0000000..775c48d --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Exception/LengthException.php @@ -0,0 +1,7 @@ +started) { + return; + } + + $this->started = true; + $this->drain(); + } + + /** + * @param mixed $cancellable + */ + public function enqueue($cancellable): void + { + if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) { + return; + } + + $length = \array_push($this->queue, $cancellable); + + if ($this->started && 1 === $length) { + $this->drain(); + } + } + + private function drain(): void + { + for ($i = \key($this->queue); isset($this->queue[$i]); $i++) { + $cancellable = $this->queue[$i]; + assert(\method_exists($cancellable, 'cancel')); + + $exception = null; + + try { + $cancellable->cancel(); + } catch (\Throwable $exception) { + } + + unset($this->queue[$i]); + + if ($exception) { + throw $exception; + } + } + + $this->queue = []; + } +} diff --git a/trilhas_poo/vendor/react/promise/src/Internal/FulfilledPromise.php b/trilhas_poo/vendor/react/promise/src/Internal/FulfilledPromise.php new file mode 100644 index 0000000..8a66cff --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Internal/FulfilledPromise.php @@ -0,0 +1,90 @@ + + */ +final class FulfilledPromise implements PromiseInterface +{ + /** @var T */ + private $value; + + /** + * @param T $value + * @throws \InvalidArgumentException + */ + public function __construct($value = null) + { + if ($value instanceof PromiseInterface) { + throw new \InvalidArgumentException('You cannot create React\Promise\FulfilledPromise with a promise. Use React\Promise\resolve($promiseOrValue) instead.'); + } + + $this->value = $value; + } + + /** + * @template TFulfilled + * @param ?(callable((T is void ? null : T)): (PromiseInterface|TFulfilled)) $onFulfilled + * @return PromiseInterface<($onFulfilled is null ? T : TFulfilled)> + */ + public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface + { + if (null === $onFulfilled) { + return $this; + } + + try { + /** + * @var PromiseInterface|T $result + */ + $result = $onFulfilled($this->value); + return resolve($result); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } + } + + public function catch(callable $onRejected): PromiseInterface + { + return $this; + } + + public function finally(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->then(function ($value) use ($onFulfilledOrRejected): PromiseInterface { + /** @var T $value */ + return resolve($onFulfilledOrRejected())->then(function () use ($value) { + return $value; + }); + }); + } + + public function cancel(): void + { + } + + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->catch($onRejected); + } + + /** + * @deprecated 3.0.0 Use `finally()` instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } +} diff --git a/trilhas_poo/vendor/react/promise/src/Internal/RejectedPromise.php b/trilhas_poo/vendor/react/promise/src/Internal/RejectedPromise.php new file mode 100644 index 0000000..aa1dff3 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Internal/RejectedPromise.php @@ -0,0 +1,128 @@ + + */ +final class RejectedPromise implements PromiseInterface +{ + /** @var \Throwable */ + private $reason; + + /** @var bool */ + private $handled = false; + + /** + * @param \Throwable $reason + */ + public function __construct(\Throwable $reason) + { + $this->reason = $reason; + } + + /** @throws void */ + public function __destruct() + { + if ($this->handled) { + return; + } + + $handler = set_rejection_handler(null); + if ($handler === null) { + $message = 'Unhandled promise rejection with ' . $this->reason; + + \error_log($message); + return; + } + + try { + $handler($this->reason); + } catch (\Throwable $e) { + \preg_match('/^([^:\s]++)(.*+)$/sm', (string) $e, $match); + \assert(isset($match[1], $match[2])); + $message = 'Fatal error: Uncaught ' . $match[1] . ' from unhandled promise rejection handler' . $match[2]; + + \error_log($message); + exit(255); + } + } + + /** + * @template TRejected + * @param ?callable $onFulfilled + * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected + * @return PromiseInterface<($onRejected is null ? never : TRejected)> + */ + public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface + { + if (null === $onRejected) { + return $this; + } + + $this->handled = true; + + try { + return resolve($onRejected($this->reason)); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } + } + + /** + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected): PromiseInterface + { + if (!_checkTypehint($onRejected, $this->reason)) { + return $this; + } + + /** + * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected + */ + return $this->then(null, $onRejected); + } + + public function finally(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->then(null, function (\Throwable $reason) use ($onFulfilledOrRejected): PromiseInterface { + return resolve($onFulfilledOrRejected())->then(function () use ($reason): PromiseInterface { + return new RejectedPromise($reason); + }); + }); + } + + public function cancel(): void + { + $this->handled = true; + } + + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->catch($onRejected); + } + + /** + * @deprecated 3.0.0 Use `always()` instead + * @see self::always() + */ + public function always(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } +} diff --git a/trilhas_poo/vendor/react/promise/src/Promise.php b/trilhas_poo/vendor/react/promise/src/Promise.php new file mode 100644 index 0000000..0828674 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/Promise.php @@ -0,0 +1,304 @@ + + */ +final class Promise implements PromiseInterface +{ + /** @var (callable(callable(T):void,callable(\Throwable):void):void)|null */ + private $canceller; + + /** @var ?PromiseInterface */ + private $result; + + /** @var list):void> */ + private $handlers = []; + + /** @var int */ + private $requiredCancelRequests = 0; + + /** @var bool */ + private $cancelled = false; + + /** + * @param callable(callable(T):void,callable(\Throwable):void):void $resolver + * @param (callable(callable(T):void,callable(\Throwable):void):void)|null $canceller + */ + public function __construct(callable $resolver, ?callable $canceller = null) + { + $this->canceller = $canceller; + + // Explicitly overwrite arguments with null values before invoking + // resolver function. This ensure that these arguments do not show up + // in the stack trace in PHP 7+ only. + $cb = $resolver; + $resolver = $canceller = null; + $this->call($cb); + } + + public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface + { + if (null !== $this->result) { + return $this->result->then($onFulfilled, $onRejected); + } + + if (null === $this->canceller) { + return new static($this->resolver($onFulfilled, $onRejected)); + } + + // This promise has a canceller, so we create a new child promise which + // has a canceller that invokes the parent canceller if all other + // followers are also cancelled. We keep a reference to this promise + // instance for the static canceller function and clear this to avoid + // keeping a cyclic reference between parent and follower. + $parent = $this; + ++$parent->requiredCancelRequests; + + return new static( + $this->resolver($onFulfilled, $onRejected), + static function () use (&$parent): void { + assert($parent instanceof self); + --$parent->requiredCancelRequests; + + if ($parent->requiredCancelRequests <= 0) { + $parent->cancel(); + } + + $parent = null; + } + ); + } + + /** + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected): PromiseInterface + { + return $this->then(null, static function (\Throwable $reason) use ($onRejected) { + if (!_checkTypehint($onRejected, $reason)) { + return new RejectedPromise($reason); + } + + /** + * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected + */ + return $onRejected($reason); + }); + } + + public function finally(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->then(static function ($value) use ($onFulfilledOrRejected): PromiseInterface { + /** @var T $value */ + return resolve($onFulfilledOrRejected())->then(function () use ($value) { + return $value; + }); + }, static function (\Throwable $reason) use ($onFulfilledOrRejected): PromiseInterface { + return resolve($onFulfilledOrRejected())->then(function () use ($reason): RejectedPromise { + return new RejectedPromise($reason); + }); + }); + } + + public function cancel(): void + { + $this->cancelled = true; + $canceller = $this->canceller; + $this->canceller = null; + + $parentCanceller = null; + + if (null !== $this->result) { + // Forward cancellation to rejected promise to avoid reporting unhandled rejection + if ($this->result instanceof RejectedPromise) { + $this->result->cancel(); + } + + // Go up the promise chain and reach the top most promise which is + // itself not following another promise + $root = $this->unwrap($this->result); + + // Return if the root promise is already resolved or a + // FulfilledPromise or RejectedPromise + if (!$root instanceof self || null !== $root->result) { + return; + } + + $root->requiredCancelRequests--; + + if ($root->requiredCancelRequests <= 0) { + $parentCanceller = [$root, 'cancel']; + } + } + + if (null !== $canceller) { + $this->call($canceller); + } + + // For BC, we call the parent canceller after our own canceller + if ($parentCanceller) { + $parentCanceller(); + } + } + + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->catch($onRejected); + } + + /** + * @deprecated 3.0.0 Use `finally()` instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected): PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } + + private function resolver(?callable $onFulfilled = null, ?callable $onRejected = null): callable + { + return function (callable $resolve, callable $reject) use ($onFulfilled, $onRejected): void { + $this->handlers[] = static function (PromiseInterface $promise) use ($onFulfilled, $onRejected, $resolve, $reject): void { + $promise = $promise->then($onFulfilled, $onRejected); + + if ($promise instanceof self && $promise->result === null) { + $promise->handlers[] = static function (PromiseInterface $promise) use ($resolve, $reject): void { + $promise->then($resolve, $reject); + }; + } else { + $promise->then($resolve, $reject); + } + }; + }; + } + + private function reject(\Throwable $reason): void + { + if (null !== $this->result) { + return; + } + + $this->settle(reject($reason)); + } + + /** + * @param PromiseInterface $result + */ + private function settle(PromiseInterface $result): void + { + $result = $this->unwrap($result); + + if ($result === $this) { + $result = new RejectedPromise( + new \LogicException('Cannot resolve a promise with itself.') + ); + } + + if ($result instanceof self) { + $result->requiredCancelRequests++; + } else { + // Unset canceller only when not following a pending promise + $this->canceller = null; + } + + $handlers = $this->handlers; + + $this->handlers = []; + $this->result = $result; + + foreach ($handlers as $handler) { + $handler($result); + } + + // Forward cancellation to rejected promise to avoid reporting unhandled rejection + if ($this->cancelled && $result instanceof RejectedPromise) { + $result->cancel(); + } + } + + /** + * @param PromiseInterface $promise + * @return PromiseInterface + */ + private function unwrap(PromiseInterface $promise): PromiseInterface + { + while ($promise instanceof self && null !== $promise->result) { + /** @var PromiseInterface $promise */ + $promise = $promise->result; + } + + return $promise; + } + + /** + * @param callable(callable(mixed):void,callable(\Throwable):void):void $cb + */ + private function call(callable $cb): void + { + // Explicitly overwrite argument with null value. This ensure that this + // argument does not show up in the stack trace in PHP 7+ only. + $callback = $cb; + $cb = null; + + // Use reflection to inspect number of arguments expected by this callback. + // We did some careful benchmarking here: Using reflection to avoid unneeded + // function arguments is actually faster than blindly passing them. + // Also, this helps avoiding unnecessary function arguments in the call stack + // if the callback creates an Exception (creating garbage cycles). + if (\is_array($callback)) { + $ref = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $ref = new \ReflectionMethod($callback, '__invoke'); + } else { + assert($callback instanceof \Closure || \is_string($callback)); + $ref = new \ReflectionFunction($callback); + } + $args = $ref->getNumberOfParameters(); + + try { + if ($args === 0) { + $callback(); + } else { + // Keep references to this promise instance for the static resolve/reject functions. + // By using static callbacks that are not bound to this instance + // and passing the target promise instance by reference, we can + // still execute its resolving logic and still clear this + // reference when settling the promise. This helps avoiding + // garbage cycles if any callback creates an Exception. + // These assumptions are covered by the test suite, so if you ever feel like + // refactoring this, go ahead, any alternative suggestions are welcome! + $target =& $this; + + $callback( + static function ($value) use (&$target): void { + if ($target !== null) { + $target->settle(resolve($value)); + $target = null; + } + }, + static function (\Throwable $reason) use (&$target): void { + if ($target !== null) { + $target->reject($reason); + $target = null; + } + } + ); + } + } catch (\Throwable $e) { + $target = null; + $this->reject($e); + } + } +} diff --git a/trilhas_poo/vendor/react/promise/src/PromiseInterface.php b/trilhas_poo/vendor/react/promise/src/PromiseInterface.php new file mode 100644 index 0000000..5869f76 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/PromiseInterface.php @@ -0,0 +1,152 @@ +|TFulfilled)) $onFulfilled + * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected + * @return PromiseInterface<($onRejected is null ? ($onFulfilled is null ? T : TFulfilled) : ($onFulfilled is null ? T|TRejected : TFulfilled|TRejected))> + */ + public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface; + + /** + * Registers a rejection handler for promise. It is a shortcut for: + * + * ```php + * $promise->then(null, $onRejected); + * ``` + * + * Additionally, you can type hint the `$reason` argument of `$onRejected` to catch + * only specific errors. + * + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected): PromiseInterface; + + /** + * Allows you to execute "cleanup" type tasks in a promise chain. + * + * It arranges for `$onFulfilledOrRejected` to be called, with no arguments, + * when the promise is either fulfilled or rejected. + * + * * If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will fulfill with the same value as `$promise`. + * * If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * * If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will reject with the same reason as `$promise`. + * * If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * + * `finally()` behaves similarly to the synchronous finally statement. When combined + * with `catch()`, `finally()` allows you to write code that is similar to the familiar + * synchronous catch/finally pair. + * + * Consider the following synchronous code: + * + * ```php + * try { + * return doSomething(); + * } catch(\Exception $e) { + * return handleError($e); + * } finally { + * cleanup(); + * } + * ``` + * + * Similar asynchronous code (with `doSomething()` that returns a promise) can be + * written: + * + * ```php + * return doSomething() + * ->catch('handleError') + * ->finally('cleanup'); + * ``` + * + * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected + * @return PromiseInterface + */ + public function finally(callable $onFulfilledOrRejected): PromiseInterface; + + /** + * The `cancel()` method notifies the creator of the promise that there is no + * further interest in the results of the operation. + * + * Once a promise is settled (either fulfilled or rejected), calling `cancel()` on + * a promise has no effect. + * + * @return void + */ + public function cancel(): void; + + /** + * [Deprecated] Registers a rejection handler for a promise. + * + * This method continues to exist only for BC reasons and to ease upgrading + * between versions. It is an alias for: + * + * ```php + * $promise->catch($onRejected); + * ``` + * + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + * @deprecated 3.0.0 Use catch() instead + * @see self::catch() + */ + public function otherwise(callable $onRejected): PromiseInterface; + + /** + * [Deprecated] Allows you to execute "cleanup" type tasks in a promise chain. + * + * This method continues to exist only for BC reasons and to ease upgrading + * between versions. It is an alias for: + * + * ```php + * $promise->finally($onFulfilledOrRejected); + * ``` + * + * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected + * @return PromiseInterface + * @deprecated 3.0.0 Use finally() instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected): PromiseInterface; +} diff --git a/trilhas_poo/vendor/react/promise/src/functions.php b/trilhas_poo/vendor/react/promise/src/functions.php new file mode 100644 index 0000000..214aad6 --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/functions.php @@ -0,0 +1,345 @@ +|T $promiseOrValue + * @return PromiseInterface + */ +function resolve($promiseOrValue): PromiseInterface +{ + if ($promiseOrValue instanceof PromiseInterface) { + return $promiseOrValue; + } + + if (\is_object($promiseOrValue) && \method_exists($promiseOrValue, 'then')) { + $canceller = null; + + if (\method_exists($promiseOrValue, 'cancel')) { + $canceller = [$promiseOrValue, 'cancel']; + assert(\is_callable($canceller)); + } + + /** @var Promise */ + return new Promise(function (callable $resolve, callable $reject) use ($promiseOrValue): void { + $promiseOrValue->then($resolve, $reject); + }, $canceller); + } + + return new FulfilledPromise($promiseOrValue); +} + +/** + * Creates a rejected promise for the supplied `$reason`. + * + * If `$reason` is a value, it will be the rejection value of the + * returned promise. + * + * If `$reason` is a promise, its completion value will be the rejected + * value of the returned promise. + * + * This can be useful in situations where you need to reject a promise without + * throwing an exception. For example, it allows you to propagate a rejection with + * the value of another promise. + * + * @return PromiseInterface + */ +function reject(\Throwable $reason): PromiseInterface +{ + return new RejectedPromise($reason); +} + +/** + * Returns a promise that will resolve only once all the items in + * `$promisesOrValues` have resolved. The resolution value of the returned promise + * will be an array containing the resolution values of each of the items in + * `$promisesOrValues`. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface> + */ +function all(iterable $promisesOrValues): PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + + /** @var Promise> */ + return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { + $toResolve = 0; + /** @var bool */ + $continue = true; + $values = []; + + foreach ($promisesOrValues as $i => $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + $values[$i] = null; + ++$toResolve; + + resolve($promiseOrValue)->then( + function ($value) use ($i, &$values, &$toResolve, &$continue, $resolve): void { + $values[$i] = $value; + + if (0 === --$toResolve && !$continue) { + $resolve($values); + } + }, + function (\Throwable $reason) use (&$continue, $reject): void { + $continue = false; + $reject($reason); + } + ); + + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + + $continue = false; + if ($toResolve === 0) { + $resolve($values); + } + }, $cancellationQueue); +} + +/** + * Initiates a competitive race that allows one winner. Returns a promise which is + * resolved in the same way the first settled promise resolves. + * + * The returned promise will become **infinitely pending** if `$promisesOrValues` + * contains 0 items. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface + */ +function race(iterable $promisesOrValues): PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + + /** @var Promise */ + return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { + $continue = true; + + foreach ($promisesOrValues as $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + + resolve($promiseOrValue)->then($resolve, $reject)->finally(function () use (&$continue): void { + $continue = false; + }); + + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + }, $cancellationQueue); +} + +/** + * Returns a promise that will resolve when any one of the items in + * `$promisesOrValues` resolves. The resolution value of the returned promise + * will be the resolution value of the triggering item. + * + * The returned promise will only reject if *all* items in `$promisesOrValues` are + * rejected. The rejection value will be an array of all rejection reasons. + * + * The returned promise will also reject with a `React\Promise\Exception\LengthException` + * if `$promisesOrValues` contains 0 items. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface + */ +function any(iterable $promisesOrValues): PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + + /** @var Promise */ + return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { + $toReject = 0; + $continue = true; + $reasons = []; + + foreach ($promisesOrValues as $i => $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + ++$toReject; + + resolve($promiseOrValue)->then( + function ($value) use ($resolve, &$continue): void { + $continue = false; + $resolve($value); + }, + function (\Throwable $reason) use ($i, &$reasons, &$toReject, $reject, &$continue): void { + $reasons[$i] = $reason; + + if (0 === --$toReject && !$continue) { + $reject(new CompositeException( + $reasons, + 'All promises rejected.' + )); + } + } + ); + + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + + $continue = false; + if ($toReject === 0 && !$reasons) { + $reject(new Exception\LengthException( + 'Must contain at least 1 item but contains only 0 items.' + )); + } elseif ($toReject === 0) { + $reject(new CompositeException( + $reasons, + 'All promises rejected.' + )); + } + }, $cancellationQueue); +} + +/** + * Sets the global rejection handler for unhandled promise rejections. + * + * Note that rejected promises should always be handled similar to how any + * exceptions should always be caught in a `try` + `catch` block. If you remove + * the last reference to a rejected promise that has not been handled, it will + * report an unhandled promise rejection. See also the [`reject()` function](#reject) + * for more details. + * + * The `?callable $callback` argument MUST be a valid callback function that + * accepts a single `Throwable` argument or a `null` value to restore the + * default promise rejection handler. The return value of the callback function + * will be ignored and has no effect, so you SHOULD return a `void` value. The + * callback function MUST NOT throw or the program will be terminated with a + * fatal error. + * + * The function returns the previous rejection handler or `null` if using the + * default promise rejection handler. + * + * The default promise rejection handler will log an error message plus its + * stack trace: + * + * ```php + * // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 + * React\Promise\reject(new RuntimeException('Unhandled')); + * ``` + * + * The promise rejection handler may be used to use customize the log message or + * write to custom log targets. As a rule of thumb, this function should only be + * used as a last resort and promise rejections are best handled with either the + * [`then()` method](#promiseinterfacethen), the + * [`catch()` method](#promiseinterfacecatch), or the + * [`finally()` method](#promiseinterfacefinally). + * See also the [`reject()` function](#reject) for more details. + * + * @param callable(\Throwable):void|null $callback + * @return callable(\Throwable):void|null + */ +function set_rejection_handler(?callable $callback): ?callable +{ + static $current = null; + $previous = $current; + $current = $callback; + + return $previous; +} + +/** + * @internal + */ +function _checkTypehint(callable $callback, \Throwable $reason): bool +{ + if (\is_array($callback)) { + $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $callbackReflection = new \ReflectionMethod($callback, '__invoke'); + } else { + assert($callback instanceof \Closure || \is_string($callback)); + $callbackReflection = new \ReflectionFunction($callback); + } + + $parameters = $callbackReflection->getParameters(); + + if (!isset($parameters[0])) { + return true; + } + + $expectedException = $parameters[0]; + + // Extract the type of the argument and handle different possibilities + $type = $expectedException->getType(); + + $isTypeUnion = true; + $types = []; + + switch (true) { + case $type === null: + break; + case $type instanceof \ReflectionNamedType: + $types = [$type]; + break; + case $type instanceof \ReflectionIntersectionType: + $isTypeUnion = false; + case $type instanceof \ReflectionUnionType: + $types = $type->getTypes(); + break; + default: + throw new \LogicException('Unexpected return value of ReflectionParameter::getType'); + } + + // If there is no type restriction, it matches + if (empty($types)) { + return true; + } + + foreach ($types as $type) { + + if ($type instanceof \ReflectionIntersectionType) { + foreach ($type->getTypes() as $typeToMatch) { + assert($typeToMatch instanceof \ReflectionNamedType); + $name = $typeToMatch->getName(); + if (!($matches = (!$typeToMatch->isBuiltin() && $reason instanceof $name))) { + break; + } + } + assert(isset($matches)); + } else { + assert($type instanceof \ReflectionNamedType); + $name = $type->getName(); + $matches = !$type->isBuiltin() && $reason instanceof $name; + } + + // If we look for a single match (union), we can return early on match + // If we look for a full match (intersection), we can return early on mismatch + if ($matches) { + if ($isTypeUnion) { + return true; + } + } else { + if (!$isTypeUnion) { + return false; + } + } + } + + // If we look for a single match (union) and did not return early, we matched no type and are false + // If we look for a full match (intersection) and did not return early, we matched all types and are true + return $isTypeUnion ? false : true; +} diff --git a/trilhas_poo/vendor/react/promise/src/functions_include.php b/trilhas_poo/vendor/react/promise/src/functions_include.php new file mode 100644 index 0000000..bd0c54f --- /dev/null +++ b/trilhas_poo/vendor/react/promise/src/functions_include.php @@ -0,0 +1,5 @@ +connect($uri)->then(function (React\Socket\ConnectionInterface $conn) { + // … + }, function (Exception $e) { + echo 'Error:' . $e->getMessage() . PHP_EOL; + }); + ``` + +* Improve test suite, test against PHP 8.1 release. + (#274 by @SimonFrings) + +## 1.9.0 (2021-08-03) + +* Feature: Add new `SocketServer` and deprecate `Server` to avoid class name collisions. + (#263 by @clue) + + The new `SocketServer` class has been added with an improved constructor signature + as a replacement for the previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + In its most basic form, the deprecated `Server` can now be considered an alias for new `SocketServer`. + + ```php + // deprecated + $socket = new React\Socket\Server(0); + $socket = new React\Socket\Server('127.0.0.1:8000'); + $socket = new React\Socket\Server('127.0.0.1:8000', null, $context); + $socket = new React\Socket\Server('127.0.0.1:8000', $loop, $context); + + // new + $socket = new React\Socket\SocketServer('127.0.0.1:0'); + $socket = new React\Socket\SocketServer('127.0.0.1:8000'); + $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context); + $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context, $loop); + ``` + +* Feature: Update `Connector` signature to take optional `$context` as first argument. + (#264 by @clue) + + The new signature has been added to match the new `SocketServer` and + consistently move the now commonly unneeded loop argument to the last argument. + The previous signature has been deprecated and should not be used anymore. + In its most basic form, both signatures are compatible. + + ```php + // deprecated + $connector = new React\Socket\Connector(null, $context); + $connector = new React\Socket\Connector($loop, $context); + + // new + $connector = new React\Socket\Connector($context); + $connector = new React\Socket\Connector($context, $loop); + ``` + +## 1.8.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#260 by @clue) + + ```php + // old (still supported) + $socket = new React\Socket\Server('127.0.0.1:8080', $loop); + $connector = new React\Socket\Connector($loop); + + // new (using default loop) + $socket = new React\Socket\Server('127.0.0.1:8080'); + $connector = new React\Socket\Connector(); + ``` + +## 1.7.0 (2021-06-25) + +* Feature: Support falling back to multiple DNS servers from DNS config. + (#257 by @clue) + + If you're using the default `Connector`, it will now use all DNS servers + configured on your system. If you have multiple DNS servers configured and + connectivity to the primary DNS server is broken, it will now fall back to + your other DNS servers, thus providing improved connectivity and redundancy + for broken DNS configurations. + +* Feature: Use round robin for happy eyeballs DNS responses (load balancing). + (#247 by @clue) + + If you're using the default `Connector`, it will now randomize the order of + the IP addresses resolved via DNS when connecting. This allows the load to + be distributed more evenly across all returned IP addresses. This can be + used as a very basic DNS load balancing mechanism. + +* Internal improvement to avoid unhandled rejection for future Promise API. + (#258 by @clue) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#254 by @SimonFrings) + +## 1.6.0 (2020-08-28) + +* Feature: Support upcoming PHP 8 release. + (#246 by @clue) + +* Feature: Change default socket backlog size to 511. + (#242 by @clue) + +* Fix: Fix closing connection when cancelling during TLS handshake. + (#241 by @clue) + +* Fix: Fix blocking during possible `accept()` race condition + when multiple socket servers listen on same socket address. + (#244 by @clue) + +* Improve test suite, update PHPUnit config and add full core team to the license. + (#243 by @SimonFrings and #245 by @WyriHaximus) + +## 1.5.0 (2020-07-01) + +* Feature / Fix: Improve error handling and reporting for happy eyeballs and + immediately try next connection when one connection attempt fails. + (#230, #231, #232 and #233 by @clue) + + Error messages for failed connection attempts now include more details to + ease debugging. Additionally, the happy eyeballs algorithm has been improved + to avoid having to wait for some timers to expire which significantly + improves connection setup times (in particular when IPv6 isn't available). + +* Improve test suite, minor code cleanup and improve code coverage to 100%. + Update to PHPUnit 9 and skip legacy TLS 1.0 / TLS 1.1 tests if disabled by + system. Run tests on Windows and simplify Travis CI test matrix for Mac OS X + setup and skip all TLS tests on legacy HHVM. + (#229, #235, #236 and #238 by @clue and #239 by @SimonFrings) + +## 1.4.0 (2020-03-12) + +A major new feature release, see [**release announcement**](https://clue.engineering/2020/introducing-ipv6-for-reactphp). + +* Feature: Add IPv6 support to `Connector` (implement "Happy Eyeballs" algorithm to support IPv6 probing). + IPv6 support is turned on by default, use new `happy_eyeballs` option in `Connector` to toggle behavior. + (#196, #224 and #225 by @WyriHaximus and @clue) + +* Feature: Default to using DNS cache (with max 256 entries) for `Connector`. + (#226 by @clue) + +* Add `.gitattributes` to exclude dev files from exports and some minor code style fixes. + (#219 by @reedy and #218 by @mmoreram) + +* Improve test suite to fix failing test cases when using new DNS component, + significantly improve test performance by awaiting events instead of sleeping, + exclude TLS 1.3 test on PHP 7.3, run tests on PHP 7.4 and simplify test matrix. + (#208, #209, #210, #217 and #223 by @clue) + +## 1.3.0 (2019-07-10) + +* Feature: Forward compatibility with upcoming stable DNS component. + (#206 by @clue) + +## 1.2.1 (2019-06-03) + +* Avoid uneeded fragmented TLS work around for PHP 7.3.3+ and + work around failing test case detecting EOF on TLS 1.3 socket streams. + (#201 and #202 by @clue) + +* Improve TLS certificate/passphrase example. + (#190 by @jsor) + +## 1.2.0 (2019-01-07) + +* Feature / Fix: Improve TLS 1.3 support. + (#186 by @clue) + + TLS 1.3 is now an official standard as of August 2018! :tada: + The protocol has major improvements in the areas of security, performance, and privacy. + TLS 1.3 is supported by default as of [OpenSSL 1.1.1](https://www.openssl.org/blog/blog/2018/09/11/release111/). + For example, this version ships with Ubuntu 18.10 (and newer) by default, meaning that recent installations support TLS 1.3 out of the box :shipit: + +* Fix: Avoid possibility of missing remote address when TLS handshake fails. + (#188 by @clue) + +* Improve performance by prefixing all global functions calls with `\` to skip the look up and resolve process and go straight to the global function. + (#183 by @WyriHaximus) + +* Update documentation to use full class names with namespaces. + (#187 by @clue) + +* Improve test suite to avoid some possible race conditions, + test against PHP 7.3 on Travis and + use dedicated `assertInstanceOf()` assertions. + (#185 by @clue, #178 by @WyriHaximus and #181 by @carusogabriel) + +## 1.1.0 (2018-10-01) + +* Feature: Improve error reporting for failed connection attempts and improve + cancellation forwarding during DNS lookup, TCP/IP connection or TLS handshake. + (#168, #169, #170, #171, #176 and #177 by @clue) + + All error messages now always contain a reference to the remote URI to give + more details which connection actually failed and the reason for this error. + Accordingly, failures during DNS lookup will now mention both the remote URI + as well as the DNS error reason. TCP/IP connection issues and errors during + a secure TLS handshake will both mention the remote URI as well as the + underlying socket error. Similarly, lost/dropped connections during a TLS + handshake will now report a lost connection instead of an empty error reason. + + For most common use cases this means that simply reporting the `Exception` + message should give the most relevant details for any connection issues: + + ```php + $promise = $connector->connect('tls://example.com:443'); + $promise->then(function (ConnectionInterface $conn) use ($loop) { + // … + }, function (Exception $e) { + echo $e->getMessage(); + }); + ``` + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.8.12 release. + +## 0.8.12 (2018-06-11) + +* Feature: Improve memory consumption for failed and cancelled connection attempts. + (#161 by @clue) + +* Improve test suite to fix Travis config to test against legacy PHP 5.3 again. + (#162 by @clue) + +## 0.8.11 (2018-04-24) + +* Feature: Improve memory consumption for cancelled connection attempts and + simplify skipping DNS lookup when connecting to IP addresses. + (#159 and #160 by @clue) + +## 0.8.10 (2018-02-28) + +* Feature: Update DNS dependency to support loading system default DNS + nameserver config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac/Docker/WSL and WMIC on Windows) + (#152 by @clue) + + This means that connecting to hosts that are managed by a local DNS server, + such as a corporate DNS server or when using Docker containers, will now + work as expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('intranet.example:80')->then(function ($connection) { + // … + }); + ``` + +## 0.8.9 (2018-01-18) + +* Feature: Support explicitly choosing TLS version to negotiate with remote side + by respecting `crypto_method` context parameter for all classes. + (#149 by @clue) + + By default, all connector and server classes support TLSv1.0+ and exclude + support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly + choose the TLS version you want to negotiate with the remote side: + + ```php + // new: now supports 'crypto_method` context parameter for all classes + $connector = new Connector($loop, array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) + )); + ``` + +* Minor internal clean up to unify class imports + (#148 by @clue) + +## 0.8.8 (2018-01-06) + +* Improve test suite by adding test group to skip integration tests relying on + internet connection and fix minor documentation typo. + (#146 by @clue and #145 by @cn007b) + +## 0.8.7 (2017-12-24) + +* Fix: Fix closing socket resource before removing from loop + (#141 by @clue) + + This fixes the root cause of an uncaught `Exception` that only manifested + itself after the recent Stream v0.7.4 component update and only if you're + using `ext-event` (`ExtEventLoop`). + +* Improve test suite by testing against PHP 7.2 + (#140 by @carusogabriel) + +## 0.8.6 (2017-11-18) + +* Feature: Add Unix domain socket (UDS) support to `Server` with `unix://` URI scheme + and add advanced `UnixServer` class. + (#120 by @andig) + + ```php + // new: Server now supports "unix://" scheme + $server = new Server('unix:///tmp/server.sock', $loop); + + // new: advanced usage + $server = new UnixServer('/tmp/server.sock', $loop); + ``` + +* Restructure examples to ease getting started + (#136 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#133 by @gabriel-caruso and #134 by @clue) + +## 0.8.5 (2017-10-23) + +* Fix: Work around PHP bug with Unix domain socket (UDS) paths for Mac OS X + (#123 by @andig) + +* Fix: Fix `SecureServer` to return `null` URI if server socket is already closed + (#129 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit v5 and + forward compatibility with upcoming EventLoop releases in tests and + test Mac OS X on Travis + (#122 by @andig and #125, #127 and #130 by @clue) + +* Readme improvements + (#118 by @jsor) + +## 0.8.4 (2017-09-16) + +* Feature: Add `FixedUriConnector` decorator to use fixed, preconfigured URI instead + (#117 by @clue) + + This can be useful for consumers that do not support certain URIs, such as + when you want to explicitly connect to a Unix domain socket (UDS) path + instead of connecting to a default address assumed by an higher-level API: + + ```php + $connector = new FixedUriConnector( + 'unix:///var/run/docker.sock', + new UnixConnector($loop) + ); + + // destination will be ignored, actually connects to Unix domain socket + $promise = $connector->connect('localhost:80'); + ``` + +## 0.8.3 (2017-09-08) + +* Feature: Reduce memory consumption for failed connections + (#113 by @valga) + +* Fix: Work around write chunk size for TLS streams for PHP < 7.1.14 + (#114 by @clue) + +## 0.8.2 (2017-08-25) + +* Feature: Update DNS dependency to support hosts file on all platforms + (#112 by @clue) + + This means that connecting to hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('localhost:8080')->then(function ($connection) { + // … + }); + ``` + +## 0.8.1 (2017-08-15) + +* Feature: Forward compatibility with upcoming EventLoop v1.0 and v0.5 and + target evenement 3.0 a long side 2.0 and 1.0 + (#104 by @clue and #111 by @WyriHaximus) + +* Improve test suite by locking Travis distro so new defaults will not break the build and + fix HHVM build for now again and ignore future HHVM build errors + (#109 and #110 by @clue) + +* Minor documentation fixes + (#103 by @christiaan and #108 by @hansott) + +## 0.8.0 (2017-05-09) + +* Feature: New `Server` class now acts as a facade for existing server classes + and renamed old `Server` to `TcpServer` for advanced usage. + (#96 and #97 by @clue) + + The `Server` class is now the main class in this package that implements the + `ServerInterface` and allows you to accept incoming streaming connections, + such as plaintext TCP/IP or secure TLS connection streams. + + > This is not a BC break and consumer code does not have to be updated. + +* Feature / BC break: All addresses are now URIs that include the URI scheme + (#98 by @clue) + + ```diff + - $parts = parse_url('tcp://' . $conn->getRemoteAddress()); + + $parts = parse_url($conn->getRemoteAddress()); + ``` + +* Fix: Fix `unix://` addresses for Unix domain socket (UDS) paths + (#100 by @clue) + +* Feature: Forward compatibility with Stream v1.0 and v0.7 + (#99 by @clue) + +## 0.7.2 (2017-04-24) + +* Fix: Work around latest PHP 7.0.18 and 7.1.4 no longer accepting full URIs + (#94 by @clue) + +## 0.7.1 (2017-04-10) + +* Fix: Ignore HHVM errors when closing connection that is already closing + (#91 by @clue) + +## 0.7.0 (2017-04-10) + +* Feature: Merge SocketClient component into this component + (#87 by @clue) + + This means that this package now provides async, streaming plaintext TCP/IP + and secure TLS socket server and client connections for ReactPHP. + + ``` + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + + Accordingly, the `ConnectionInterface` is now used to represent both incoming + server side connections as well as outgoing client side connections. + + If you've previously used the SocketClient component to establish outgoing + client connections, upgrading should take no longer than a few minutes. + All classes have been merged as-is from the latest `v0.7.0` release with no + other changes, so you can simply update your code to use the updated namespace + like this: + + ```php + // old from SocketClient component and namespace + $connector = new React\SocketClient\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + + // new + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + +## 0.6.0 (2017-04-04) + +* Feature: Add `LimitingServer` to limit and keep track of open connections + (#86 by @clue) + + ```php + $server = new Server(0, $loop); + $server = new LimitingServer($server, 100); + + $server->on('connection', function (ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … + }); + ``` + +* Feature / BC break: Add `pause()` and `resume()` methods to limit active + connections + (#84 by @clue) + + ```php + $server = new Server(0, $loop); + $server->pause(); + + $loop->addTimer(1.0, function() use ($server) { + $server->resume(); + }); + ``` + +## 0.5.1 (2017-03-09) + +* Feature: Forward compatibility with Stream v0.5 and upcoming v0.6 + (#79 by @clue) + +## 0.5.0 (2017-02-14) + +* Feature / BC break: Replace `listen()` call with URIs passed to constructor + and reject listening on hostnames with `InvalidArgumentException` + and replace `ConnectionException` with `RuntimeException` for consistency + (#61, #66 and #72 by @clue) + + ```php + // old + $server = new Server($loop); + $server->listen(8080); + + // new + $server = new Server(8080, $loop); + ``` + + Similarly, you can now pass a full listening URI to the constructor to change + the listening host: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, '127.0.0.1'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + Trying to start listening on (DNS) host names will now throw an + `InvalidArgumentException`, use IP addresses instead: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, 'localhost'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + If trying to listen fails (such as if port is already in use or port below + 1024 may require root access etc.), it will now throw a `RuntimeException`, + the `ConnectionException` class has been removed: + + ```php + // old: throws React\Socket\ConnectionException + $server = new Server($loop); + $server->listen(80); + + // new: throws RuntimeException + $server = new Server(80, $loop); + ``` + +* Feature / BC break: Rename `shutdown()` to `close()` for consistency throughout React + (#62 by @clue) + + ```php + // old + $server->shutdown(); + + // new + $server->close(); + ``` + +* Feature / BC break: Replace `getPort()` with `getAddress()` + (#67 by @clue) + + ```php + // old + echo $server->getPort(); // 8080 + + // new + echo $server->getAddress(); // 127.0.0.1:8080 + ``` + +* Feature / BC break: `getRemoteAddress()` returns full address instead of only IP + (#65 by @clue) + + ```php + // old + echo $connection->getRemoteAddress(); // 192.168.0.1 + + // new + echo $connection->getRemoteAddress(); // 192.168.0.1:51743 + ``` + +* Feature / BC break: Add `getLocalAddress()` method + (#68 by @clue) + + ```php + echo $connection->getLocalAddress(); // 127.0.0.1:8080 + ``` + +* BC break: The `Server` and `SecureServer` class are now marked `final` + and you can no longer `extend` them + (which was never documented or recommended anyway). + Public properties and event handlers are now internal only. + Please use composition instead of extension. + (#71, #70 and #69 by @clue) + +## 0.4.6 (2017-01-26) + +* Feature: Support socket context options passed to `Server` + (#64 by @clue) + +* Fix: Properly return `null` for unknown addresses + (#63 by @clue) + +* Improve documentation for `ServerInterface` and lock test suite requirements + (#60 by @clue, #57 by @shaunbramley) + +## 0.4.5 (2017-01-08) + +* Feature: Add `SecureServer` for secure TLS connections + (#55 by @clue) + +* Add functional integration tests + (#54 by @clue) + +## 0.4.4 (2016-12-19) + +* Feature / Fix: `ConnectionInterface` should extend `DuplexStreamInterface` + documentation + (#50 by @clue) + +* Feature / Fix: Improve test suite and switch to normal stream handler + (#51 by @clue) + +* Feature: Add examples + (#49 by @clue) + +## 0.4.3 (2016-03-01) + +* Bug fix: Suppress errors on stream_socket_accept to prevent PHP from crashing +* Support for PHP7 and HHVM +* Support PHP 5.3 again + +## 0.4.2 (2014-05-25) + +* Verify stream is a valid resource in Connection + +## 0.4.1 (2014-04-13) + +* Bug fix: Check read buffer for data before shutdown signal and end emit (@ArtyDev) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: Reset socket to non-blocking after shutting down (PHP bug) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.3 (2013-07-08) + +* Version bump + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.1 (2013-04-21) + +* Feature: Support binding to IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.0 (2012-09-10) + +* Bump React dependencies to v0.2 + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/trilhas_poo/vendor/react/socket/LICENSE b/trilhas_poo/vendor/react/socket/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/socket/README.md b/trilhas_poo/vendor/react/socket/README.md new file mode 100644 index 0000000..092590a --- /dev/null +++ b/trilhas_poo/vendor/react/socket/README.md @@ -0,0 +1,1564 @@ +# Socket + +[![CI status](https://github.com/reactphp/socket/workflows/CI/badge.svg)](https://github.com/reactphp/socket/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/socket?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/socket) + +Async, streaming plaintext TCP/IP and secure TLS socket server and client +connections for [ReactPHP](https://reactphp.org/). + +The socket library provides re-usable interfaces for a socket-layer +server and client based on the [`EventLoop`](https://github.com/reactphp/event-loop) +and [`Stream`](https://github.com/reactphp/stream) components. +Its server component allows you to build networking servers that accept incoming +connections from networking clients (such as an HTTP server). +Its client component allows you to build networking clients that establish +outgoing connections to networking servers (such as an HTTP or database client). +This library provides async, streaming means for all of this, so you can +handle multiple concurrent connections without blocking. + +**Table of Contents** + +* [Quickstart example](#quickstart-example) +* [Connection usage](#connection-usage) + * [ConnectionInterface](#connectioninterface) + * [getRemoteAddress()](#getremoteaddress) + * [getLocalAddress()](#getlocaladdress) +* [Server usage](#server-usage) + * [ServerInterface](#serverinterface) + * [connection event](#connection-event) + * [error event](#error-event) + * [getAddress()](#getaddress) + * [pause()](#pause) + * [resume()](#resume) + * [close()](#close) + * [SocketServer](#socketserver) + * [Advanced server usage](#advanced-server-usage) + * [TcpServer](#tcpserver) + * [SecureServer](#secureserver) + * [UnixServer](#unixserver) + * [LimitingServer](#limitingserver) + * [getConnections()](#getconnections) +* [Client usage](#client-usage) + * [ConnectorInterface](#connectorinterface) + * [connect()](#connect) + * [Connector](#connector) + * [Advanced client usage](#advanced-client-usage) + * [TcpConnector](#tcpconnector) + * [HappyEyeBallsConnector](#happyeyeballsconnector) + * [DnsConnector](#dnsconnector) + * [SecureConnector](#secureconnector) + * [TimeoutConnector](#timeoutconnector) + * [UnixConnector](#unixconnector) + * [FixUriConnector](#fixeduriconnector) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +Here is a server that closes the connection if you send it anything: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); + +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write("Hello " . $connection->getRemoteAddress() . "!\n"); + $connection->write("Welcome to this amazing server!\n"); + $connection->write("Here's a tip: don't say anything.\n"); + + $connection->on('data', function ($data) use ($connection) { + $connection->close(); + }); +}); +``` + +See also the [examples](examples). + +Here's a client that outputs the output of said server and then attempts to +send it a string: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->pipe(new React\Stream\WritableResourceStream(STDOUT)); + $connection->write("Hello World!\n"); +}, function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +## Connection usage + +### ConnectionInterface + +The `ConnectionInterface` is used to represent any incoming and outgoing +connection, such as a normal TCP/IP connection. + +An incoming or outgoing connection is a duplex stream (both readable and +writable) that implements React's +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). +It contains additional properties for the local and remote address (client IP) +where this connection has been established to/from. + +Most commonly, instances implementing this `ConnectionInterface` are emitted +by all classes implementing the [`ServerInterface`](#serverinterface) and +used by all classes implementing the [`ConnectorInterface`](#connectorinterface). + +Because the `ConnectionInterface` implements the underlying +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface) +you can use any of its events and methods as usual: + +```php +$connection->on('data', function ($chunk) { + echo $chunk; +}); + +$connection->on('end', function () { + echo 'ended'; +}); + +$connection->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage(); +}); + +$connection->on('close', function () { + echo 'closed'; +}); + +$connection->write($data); +$connection->end($data = null); +$connection->close(); +// … +``` + +For more details, see the +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + +#### getRemoteAddress() + +The `getRemoteAddress(): ?string` method returns the full remote address +(URI) where this connection has been established with. + +```php +$address = $connection->getRemoteAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the remote address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based connection and you only want the remote IP, you may +use something like this: + +```php +$address = $connection->getRemoteAddress(); +$ip = trim(parse_url($address, PHP_URL_HOST), '[]'); +echo 'Connection with ' . $ip . PHP_EOL; +``` + +#### getLocalAddress() + +The `getLocalAddress(): ?string` method returns the full local address +(URI) where this connection has been established with. + +```php +$address = $connection->getLocalAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the local address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +This method complements the [`getRemoteAddress()`](#getremoteaddress) method, +so they should not be confused. + +If your `TcpServer` instance is listening on multiple interfaces (e.g. using +the address `0.0.0.0`), you can use this method to find out which interface +actually accepted this connection (such as a public or local interface). + +If your system has multiple interfaces (e.g. a WAN and a LAN interface), +you can use this method to find out which interface was actually +used for this connection. + +## Server usage + +### ServerInterface + +The `ServerInterface` is responsible for providing an interface for accepting +incoming streaming connections, such as a normal TCP/IP connection. + +Most higher-level components (such as a HTTP server) accept an instance +implementing this interface to accept incoming streaming connections. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. +This means that you SHOULD typehint against this interface instead of a concrete +implementation of this interface. + +Besides defining a few methods, this interface also implements the +[`EventEmitterInterface`](https://github.com/igorw/evenement) +which allows you to react to certain events. + +#### connection event + +The `connection` event will be emitted whenever a new connection has been +established, i.e. a new client connects to this server socket: + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'new connection' . PHP_EOL; +}); +``` + +See also the [`ConnectionInterface`](#connectioninterface) for more details +about handling the incoming connection. + +#### error event + +The `error` event will be emitted whenever there's an error accepting a new +connection from a client. + +```php +$socket->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that this is not a fatal error event, i.e. the server keeps listening for +new connections even after this event. + +#### getAddress() + +The `getAddress(): ?string` method can be used to +return the full address (URI) this server is currently listening on. + +```php +$address = $socket->getAddress(); +echo 'Server listening on ' . $address . PHP_EOL; +``` + +If the address can not be determined or is unknown at this time (such as +after the socket has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443` +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based server and you only want the local port, you may +use something like this: + +```php +$address = $socket->getAddress(); +$port = parse_url($address, PHP_URL_PORT); +echo 'Server listening on port ' . $port . PHP_EOL; +``` + +#### pause() + +The `pause(): void` method can be used to +pause accepting new incoming connections. + +Removes the socket resource from the EventLoop and thus stop accepting +new connections. Note that the listening socket stays active and is not +closed. + +This means that new incoming connections will stay pending in the +operating system backlog until its configurable backlog is filled. +Once the backlog is filled, the operating system may reject further +incoming connections until the backlog is drained again by resuming +to accept new connections. + +Once the server is paused, no futher `connection` events SHOULD +be emitted. + +```php +$socket->pause(); + +$socket->on('connection', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +server MAY continue emitting `connection` events. + +Unless otherwise noted, a successfully opened server SHOULD NOT start +in paused state. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### resume() + +The `resume(): void` method can be used to +resume accepting new incoming connections. + +Re-attach the socket resource to the EventLoop after a previous `pause()`. + +```php +$socket->pause(); + +Loop::addTimer(1.0, function () use ($socket) { + $socket->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### close() + +The `close(): void` method can be used to +shut down this listening socket. + +This will stop listening for new incoming connections on this socket. + +```php +echo 'Shutting down server socket' . PHP_EOL; +$socket->close(); +``` + +Calling this method more than once on the same instance is a NO-OP. + +### SocketServer + + + +The `SocketServer` class is the main class in this package that implements the +[`ServerInterface`](#serverinterface) and allows you to accept incoming +streaming connections, such as plaintext TCP/IP or secure TLS connection streams. + +In order to accept plaintext TCP/IP connections, you can simply pass a host +and port combination like this: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +Listening on the localhost address `127.0.0.1` means it will not be reachable from +outside of this system. +In order to change the host the socket is listening on, you can provide an IP +address of an interface or use the special `0.0.0.0` address to listen on all +interfaces: + +```php +$socket = new React\Socket\SocketServer('0.0.0.0:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080'); +``` + +In order to use a random port assignment, you can use the port `0`: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:0'); +$address = $socket->getAddress(); +``` + +To listen on a Unix domain socket (UDS) path, you MUST prefix the URI with the +`unix://` scheme: + +```php +$socket = new React\Socket\SocketServer('unix:///tmp/server.sock'); +``` + +In order to listen on an existing file descriptor (FD) number, you MUST prefix +the URI with `php://fd/` like this: + +```php +$socket = new React\Socket\SocketServer('php://fd/3'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$socket = new React\Socket\SocketServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\SocketServer('127.0.0.1:8080'); + +// throws RuntimeException because port is already in use +$second = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + See the exception message and code for more details about the actual error + condition. + +Optionally, you can specify [TCP socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080', array( + 'tcp' => array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true + ) +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + Passing unknown context options has no effect. + The `backlog` context option defaults to `511` unless given explicitly. + +You can start a secure TLS (formerly known as SSL) server by simply prepending +the `tls://` URI scheme. +Internally, it will wait for plaintext TCP/IP connections and then performs a +TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8080', array( + 'tls' => array( + 'local_cert' => 'server.pem' + ) +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an + incoming connection initializes its TLS context. + This implies that any invalid certificate file paths or contents will only cause + an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' + ) +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER + ) +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + The outer context array allows you to also use `tcp` (and possibly more) + context options at the same time. + Passing unknown context options has no effect. + If you do not use the `tls://` scheme, then passing `tls` context options + has no effect. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Note that the `SocketServer` class is a concrete implementation for TCP/IP sockets. + If you want to typehint in your higher-level protocol implementation, you SHOULD + use the generic [`ServerInterface`](#serverinterface) instead. + +> Changelog v1.9.0: This class has been added with an improved constructor signature + as a replacement for the previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + +### Advanced server usage + +#### TcpServer + +The `TcpServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting plaintext TCP/IP connections. + +```php +$server = new React\Socket\TcpServer(8080); +``` + +As above, the `$uri` parameter can consist of only a port, in which case the +server will default to listening on the localhost address `127.0.0.1`, +which means it will not be reachable from outside of this system. + +In order to use a random port assignment, you can use the port `0`: + +```php +$server = new React\Socket\TcpServer(0); +$address = $server->getAddress(); +``` + +In order to change the host the socket is listening on, you can provide an IP +address through the first parameter provided to the constructor, optionally +preceded by the `tcp://` scheme: + +```php +$server = new React\Socket\TcpServer('192.168.0.1:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$server = new React\Socket\TcpServer('[::1]:8080'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$server = new React\Socket\TcpServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\TcpServer(8080); + +// throws RuntimeException because port is already in use +$second = new React\Socket\TcpServer(8080); +``` + +> Note that these error conditions may vary depending on your system and/or +configuration. +See the exception message and code for more details about the actual error +condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$server = new React\Socket\TcpServer('[::1]:8080', null, array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. +The `backlog` context option defaults to `511` unless given explicitly. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### SecureServer + +The `SecureServer` class implements the [`ServerInterface`](#serverinterface) +and is responsible for providing a secure TLS (formerly known as SSL) server. + +It does so by wrapping a [`TcpServer`](#tcpserver) instance which waits for plaintext +TCP/IP connections and then performs a TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem' +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an +incoming connection initializes its TLS context. +This implies that any invalid certificate file paths or contents will only cause +an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. + +Whenever a client completes the TLS handshake, it will emit a `connection` event +with a connection instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +Whenever a client fails to perform a successful TLS handshake, it will emit an +`error` event and then close the underlying TCP/IP connection: + +```php +$server->on('error', function (Exception $e) { + echo 'Error' . $e->getMessage() . PHP_EOL; +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +Note that the `SecureServer` class is a concrete implementation for TLS sockets. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ServerInterface`](#serverinterface) instead. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Despite allowing any `ServerInterface` as first parameter, +you SHOULD pass a `TcpServer` instance as first parameter, unless you +know what you're doing. +Internally, the `SecureServer` has to set the required TLS context options on +the underlying stream resources. +These resources are not exposed through any of the interfaces defined in this +package, but only through the internal `Connection` class. +The `TcpServer` class is guaranteed to emit connections that implement +the `ConnectionInterface` and uses the internal `Connection` class in order to +expose these underlying resources. +If you use a custom `ServerInterface` and its `connection` event does not +meet this requirement, the `SecureServer` will emit an `error` event and +then close the underlying connection. + +#### UnixServer + +The `UnixServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting connections on Unix domain sockets (UDS). + +```php +$server = new React\Socket\UnixServer('/tmp/server.sock'); +``` + +As above, the `$uri` parameter can consist of only a socket path or socket path +prefixed by the `unix://` scheme. + +If the given URI appears to be valid, but listening on it fails (such as if the +socket is already in use or the file not accessible etc.), it will throw a +`RuntimeException`: + +```php +$first = new React\Socket\UnixServer('/tmp/same.sock'); + +// throws RuntimeException because socket is already in use +$second = new React\Socket\UnixServer('/tmp/same.sock'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + In particular, Zend PHP does only report "Unknown error" when the UDS path + already exists and can not be bound. You may want to check `is_file()` on the + given UDS path to report a more user-friendly error message in this case. + See the exception message and code for more details about the actual error + condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'New connection' . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### LimitingServer + +The `LimitingServer` decorator wraps a given `ServerInterface` and is responsible +for limiting and keeping track of open connections to this server instance. + +Whenever the underlying server emits a `connection` event, it will check its +limits and then either + - keep track of this connection by adding it to the list of + open connections and then forward the `connection` event + - or reject (close) the connection when its limits are exceeded and will + forward an `error` event instead. + +Whenever a connection closes, it will remove this connection from the list of +open connections. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [second example](examples) for more details. + +You have to pass a maximum number of open connections to ensure +the server will automatically reject (close) connections once this limit +is exceeded. In this case, it will emit an `error` event to inform about +this and no `connection` event will be emitted. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +You MAY pass a `null` limit in order to put no limit on the number of +open connections and keep accepting new connection until you run out of +operating system resources (such as open file handles). This may be +useful if you do not want to take care of applying a limit but still want +to use the `getConnections()` method. + +You can optionally configure the server to pause accepting new +connections once the connection limit is reached. In this case, it will +pause the underlying server and no longer process any new connections at +all, thus also no longer closing any excessive connections. +The underlying operating system is responsible for keeping a backlog of +pending connections until its limit is reached, at which point it will +start rejecting further connections. +Once the server is below the connection limit, it will continue consuming +connections from the backlog and will process any outstanding data on +each connection. +This mode may be useful for some protocols that are designed to wait for +a response message (such as HTTP), but may be less useful for other +protocols that demand immediate responses (such as a "welcome" message in +an interactive chat). + +```php +$server = new React\Socket\LimitingServer($server, 100, true); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +##### getConnections() + +The `getConnections(): ConnectionInterface[]` method can be used to +return an array with all currently active connections. + +```php +foreach ($server->getConnection() as $connection) { + $connection->write('Hi!'); +} +``` + +## Client usage + +### ConnectorInterface + +The `ConnectorInterface` is responsible for providing an interface for +establishing streaming connections, such as a normal TCP/IP connection. + +This is the main interface defined in this package and it is used throughout +React's vast ecosystem. + +Most higher-level components (such as HTTP, database or other networking +service clients) accept an instance implementing this interface to create their +TCP/IP connection to the underlying networking service. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. + +The interface only offers a single method: + +#### connect() + +The `connect(string $uri): PromiseInterface` method can be used to +create a streaming connection to the given remote address. + +It returns a [Promise](https://github.com/reactphp/promise) which either +fulfills with a stream implementing [`ConnectionInterface`](#connectioninterface) +on success or rejects with an `Exception` if the connection is not successful: + +```php +$connector->connect('google.com:443')->then( + function (React\Socket\ConnectionInterface $connection) { + // connection successfully established + }, + function (Exception $error) { + // failed to connect due to $error + } +); +``` + +See also [`ConnectionInterface`](#connectioninterface) for more details. + +The returned Promise MUST be implemented in such a way that it can be +cancelled when it is still pending. Cancelling a pending promise MUST +reject its value with an `Exception`. It SHOULD clean up any underlying +resources and references as applicable: + +```php +$promise = $connector->connect($uri); + +$promise->cancel(); +``` + +### Connector + +The `Connector` class is the main class in this package that implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create streaming connections. + +You can use this connector to create any kind of streaming connections, such +as plaintext TCP/IP, secure TLS or local Unix connection streams. + +It binds to the main event loop and can be used like this: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect($uri)->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}, function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +In order to create a plaintext TCP/IP connection, you can simply pass a host +and port combination like this: + +```php +$connector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> If you do no specify a URI scheme in the destination URI, it will assume + `tcp://` as a default and establish a plaintext TCP/IP connection. + Note that TCP/IP connections require a host and port part in the destination + URI like above, all other URI components are optional. + +In order to create a secure TLS connection, you can use the `tls://` URI scheme +like this: + +```php +$connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +In order to create a local Unix domain socket connection, you can use the +`unix://` URI scheme like this: + +```php +$connector->connect('unix:///tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, including + the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +Under the hood, the `Connector` is implemented as a *higher-level facade* +for the lower-level connectors implemented in this package. This means it +also shares all of their features and implementation details. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ConnectorInterface`](#connectorinterface) instead. + +As of `v1.4.0`, the `Connector` class defaults to using the +[happy eyeballs algorithm](https://en.wikipedia.org/wiki/Happy_Eyeballs) to +automatically connect over IPv4 or IPv6 when a hostname is given. +This automatically attempts to connect using both IPv4 and IPv6 at the same time +(preferring IPv6), thus avoiding the usual problems faced by users with imperfect +IPv6 connections or setups. +If you want to revert to the old behavior of only doing an IPv4 lookup and +only attempt a single IPv4 connection, you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'happy_eyeballs' => false +)); +``` + +Similarly, you can also affect the default DNS behavior as follows. +The `Connector` class will try to detect your system DNS settings (and uses +Google's public DNS server `8.8.8.8` as a fallback if unable to determine your +system settings) to resolve all public hostnames into underlying IP addresses by +default. +If you explicitly want to use a custom DNS server (such as a local DNS relay or +a company wide DNS server), you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => '127.0.1.1' +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +If you do not want to use a DNS resolver at all and want to connect to IP +addresses only, you can also set up your `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => false +)); + +$connector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +Advanced: If you need a custom DNS `React\Dns\Resolver\ResolverInterface` instance, you +can also set up your `Connector` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); + +$connector = new React\Socket\Connector(array( + 'dns' => $resolver +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, the `tcp://` and `tls://` URI schemes will use timeout value that +respects your `default_socket_timeout` ini setting (which defaults to 60s). +If you want a custom timeout value, you can simply pass this like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => 10.0 +)); +``` + +Similarly, if you do not want to apply a timeout at all and let the operating +system handle this, you can pass a boolean flag like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => false +)); +``` + +By default, the `Connector` supports the `tcp://`, `tls://` and `unix://` +URI schemes. If you want to explicitly prohibit any of these, you can simply +pass boolean flags like this: + +```php +// only allow secure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => false, + 'tls' => true, + 'unix' => false, +)); + +$connector->connect('tls://google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +The `tcp://` and `tls://` also accept additional context options passed to +the underlying connectors. +If you want to explicitly pass additional context options, you can simply +pass arrays of context options like this: + +```php +// allow insecure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => array( + 'bindto' => '192.168.0.1:0' + ), + 'tls' => array( + 'verify_peer' => false, + 'verify_peer_name' => false + ), +)); + +$connector->connect('tls://localhost:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$connector = new React\Socket\Connector(array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) +)); +``` + +> For more details about context options, please refer to the PHP documentation + about [socket context options](https://www.php.net/manual/en/context.socket.php) + and [SSL context options](https://www.php.net/manual/en/context.ssl.php). + +Advanced: By default, the `Connector` supports the `tcp://`, `tls://` and +`unix://` URI schemes. +For this, it sets up the required connector classes automatically. +If you want to explicitly pass custom connectors for any of these, you can simply +pass an instance implementing the `ConnectorInterface` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); +$tcp = new React\Socket\HappyEyeBallsConnector(null, new React\Socket\TcpConnector(), $resolver); + +$tls = new React\Socket\SecureConnector($tcp); + +$unix = new React\Socket\UnixConnector(); + +$connector = new React\Socket\Connector(array( + 'tcp' => $tcp, + 'tls' => $tls, + 'unix' => $unix, + + 'dns' => false, + 'timeout' => false, +)); + +$connector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> Internally, the `tcp://` connector will always be wrapped by the DNS resolver, + unless you disable DNS like in the above example. In this case, the `tcp://` + connector receives the actual hostname instead of only the resolved IP address + and is thus responsible for performing the lookup. + Internally, the automatically created `tls://` connector will always wrap the + underlying `tcp://` connector for establishing the underlying plaintext + TCP/IP connection before enabling secure TLS mode. If you want to use a custom + underlying `tcp://` connector for secure TLS connections only, you may + explicitly pass a `tls://` connector like above instead. + Internally, the `tcp://` and `tls://` connectors will always be wrapped by + `TimeoutConnector`, unless you disable timeouts like in the above example. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Changelog v1.9.0: The constructur signature has been updated to take the +> optional `$context` as the first parameter and the optional `$loop` as a second +> argument. The previous signature has been deprecated and should not be used anymore. +> +> ```php +> // constructor signature as of v1.9.0 +> $connector = new React\Socket\Connector(array $context = [], ?LoopInterface $loop = null); +> +> // legacy constructor signature before v1.9.0 +> $connector = new React\Socket\Connector(?LoopInterface $loop = null, array $context = []); +> ``` + +### Advanced client usage + +#### TcpConnector + +The `TcpConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any IP-port-combination: + +```php +$tcpConnector = new React\Socket\TcpConnector(); + +$tcpConnector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $tcpConnector->connect('127.0.0.1:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will close the underlying socket +resource, thus cancelling the pending TCP/IP connection, and reject the +resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[socket context options](https://www.php.net/manual/en/context.socket.php) +to the constructor like this: + +```php +$tcpConnector = new React\Socket\TcpConnector(null, array( + 'bindto' => '192.168.0.1:0' +)); +``` + +Note that this class only allows you to connect to IP-port-combinations. +If the given URI is invalid, does not contain a valid IP address and port +or contains any other scheme, it will reject with an +`InvalidArgumentException`: + +If the given URI appears to be valid, but connecting to it fails (such as if +the remote host rejects the connection etc.), it will reject with a +`RuntimeException`. + +If you want to connect to hostname-port-combinations, see also the following chapter. + +> Advanced usage: Internally, the `TcpConnector` allocates an empty *context* +resource for each stream resource. +If the destination URI contains a `hostname` query parameter, its value will +be used to set up the TLS peer name. +This is used by the `SecureConnector` and `DnsConnector` to verify the peer +name and can also be used if you want a custom TLS peer name. + +#### HappyEyeBallsConnector + +The `HappyEyeBallsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. Internally it implements the +happy eyeballs algorithm from [`RFC6555`](https://tools.ietf.org/html/rfc6555) and +[`RFC8305`](https://tools.ietf.org/html/rfc8305) to support IPv6 and IPv4 hostnames. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\HappyEyeBallsConnector(null, $tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookups +and/or the underlying TCP/IP connection(s) and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Internally, the `HappyEyeBallsConnector` relies on a `Resolver` to +look up the IP addresses for the given hostname. +It will then replace the hostname in the destination URI with this IP's and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The Happy Eye Balls algorithm describes looking the IPv6 and IPv4 address for +the given hostname so this connector sends out two DNS lookups for the A and +AAAA records. It then uses all IP addresses (both v6 and v4) and tries to +connect to all of them with a 50ms interval in between. Alterating between IPv6 +and IPv4 addresses. When a connection is established all the other DNS lookups +and connection attempts are cancelled. + +#### DnsConnector + +The `DnsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\DnsConnector($tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookup +and/or the underlying TCP/IP connection and reject the resulting promise. + +> Advanced usage: Internally, the `DnsConnector` relies on a `React\Dns\Resolver\ResolverInterface` +to look up the IP address for the given hostname. +It will then replace the hostname in the destination URI with this IP and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The underlying connector is thus responsible for creating a connection to the +target IP address, while this query parameter can be used to check the original +hostname and is used by the `TcpConnector` to set up the TLS peer name. +If a `hostname` is given explicitly, this query parameter will not be modified, +which can be useful if you want a custom TLS peer name. + +#### SecureConnector + +The `SecureConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create secure +TLS (formerly known as SSL) connections to any hostname-port-combination. + +It does so by decorating a given `DnsConnector` instance so that it first +creates a plaintext TCP/IP connection and then enables TLS encryption on this +stream. + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector); + +$secureConnector->connect('www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n"); + ... +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $secureConnector->connect('www.google.com:443'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying TCP/IP +connection and/or the SSL/TLS negotiation and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[SSL context options](https://www.php.net/manual/en/context.ssl.php) +to the constructor like this: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'verify_peer' => false, + 'verify_peer_name' => false +)); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT +)); +``` + +> Advanced usage: Internally, the `SecureConnector` relies on setting up the +required *context options* on the underlying stream resource. +It should therefor be used with a `TcpConnector` somewhere in the connector +stack so that it can allocate an empty *context* resource for each stream +resource and verify the peer name. +Failing to do so may result in a TLS peer name mismatch error or some hard to +trace race conditions, because all stream resources will use a single, shared +*default context* resource otherwise. + +#### TimeoutConnector + +The `TimeoutConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to add timeout +handling to any existing connector instance. + +It does so by decorating any given [`ConnectorInterface`](#connectorinterface) +instance and starting a timer that will automatically reject and abort any +underlying connection attempt if it takes too long. + +```php +$timeoutConnector = new React\Socket\TimeoutConnector($connector, 3.0); + +$timeoutConnector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + // connection succeeded within 3.0 seconds +}); +``` + +See also any of the [examples](examples). + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $timeoutConnector->connect('google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying connection +attempt, abort the timer and reject the resulting promise. + +#### UnixConnector + +The `UnixConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to connect to +Unix domain socket (UDS) paths like this: + +```php +$connector = new React\Socket\UnixConnector(); + +$connector->connect('/tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("HELLO\n"); +}); +``` + +Connecting to Unix domain sockets is an atomic operation, i.e. its promise will +settle (either resolve or reject) immediately. +As such, calling `cancel()` on the resulting promise has no effect. + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, prepended + with the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +#### FixedUriConnector + +The `FixedUriConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and decorates an existing Connector +to always use a fixed, preconfigured URI. + +This can be useful for consumers that do not support certain URIs, such as +when you want to explicitly connect to a Unix domain socket (UDS) path +instead of connecting to a default address assumed by an higher-level API: + +```php +$connector = new React\Socket\FixedUriConnector( + 'unix:///var/run/docker.sock', + new React\Socket\UnixConnector() +); + +// destination will be ignored, actually connects to Unix domain socket +$promise = $connector->connect('localhost:80'); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/socket:^1.17 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use the latest supported PHP version* for this project, +partly due to its vast performance improvements and partly because legacy PHP +versions require several workarounds as described below. + +Secure TLS connections received some major upgrades starting with PHP 5.6, with +the defaults now being more secure, while older versions required explicit +context options. +This library does not take responsibility over these context options, so it's +up to consumers of this library to take care of setting appropriate context +options as described above. + +PHP < 7.3.3 (and PHP < 7.2.15) suffers from a bug where feof() might +block with 100% CPU usage on fragmented TLS records. +We try to work around this by always consuming the complete receive +buffer at once to avoid stale data in TLS buffers. This is known to +work around high CPU usage for well-behaving peers, but this may +cause very large data chunks for high throughput scenarios. The buggy +behavior can still be triggered due to network I/O buffers or +malicious peers on affected versions, upgrading is highly recommended. + +PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big +chunks of data over TLS streams at once. +We try to work around this by limiting the write chunk size to 8192 +bytes for older PHP versions only. +This is only a work-around and has a noticable performance penalty on +affected versions. + +This project also supports running on HHVM. +Note that really old HHVM < 3.8 does not support secure TLS connections, as it +lacks the required `stream_socket_enable_crypto()` function. +As such, trying to create a secure TLS connections on affected versions will +return a rejected promise instead. +This issue is also covered by our test suite, which will skip related tests +on affected versions. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/trilhas_poo/vendor/react/socket/composer.json b/trilhas_poo/vendor/react/socket/composer.json new file mode 100644 index 0000000..b1e1d25 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/composer.json @@ -0,0 +1,52 @@ +{ + "name": "react/socket", + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": ["async", "socket", "stream", "connection", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "react/dns": "^1.13", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.6 || ^1.2.1", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3.3 || ^2", + "react/promise-stream": "^1.4", + "react/promise-timer": "^1.11" + }, + "autoload": { + "psr-4": { + "React\\Socket\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Socket\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/socket/src/Connection.php b/trilhas_poo/vendor/react/socket/src/Connection.php new file mode 100644 index 0000000..65ae26b --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/Connection.php @@ -0,0 +1,183 @@ += 70300 && \PHP_VERSION_ID < 70303); + + // PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big + // chunks of data over TLS streams at once. + // We try to work around this by limiting the write chunk size to 8192 + // bytes for older PHP versions only. + // This is only a work-around and has a noticable performance penalty on + // affected versions. Please update your PHP version. + // This applies to all streams because TLS may be enabled later on. + // See https://github.com/reactphp/socket/issues/105 + $limitWriteChunks = (\PHP_VERSION_ID < 70018 || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70104)); + + $this->input = new DuplexResourceStream( + $resource, + $loop, + $clearCompleteBuffer ? -1 : null, + new WritableResourceStream($resource, $loop, null, $limitWriteChunks ? 8192 : null) + ); + + $this->stream = $resource; + + Util::forwardEvents($this->input, $this, array('data', 'end', 'error', 'close', 'pipe', 'drain')); + + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return $this->input->isReadable(); + } + + public function isWritable() + { + return $this->input->isWritable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return $this->input->pipe($dest, $options); + } + + public function write($data) + { + return $this->input->write($data); + } + + public function end($data = null) + { + $this->input->end($data); + } + + public function close() + { + $this->input->close(); + $this->handleClose(); + $this->removeAllListeners(); + } + + public function handleClose() + { + if (!\is_resource($this->stream)) { + return; + } + + // Try to cleanly shut down socket and ignore any errors in case other + // side already closed. Underlying Stream implementation will take care + // of closing stream resource, so we otherwise keep this open here. + @\stream_socket_shutdown($this->stream, \STREAM_SHUT_RDWR); + } + + public function getRemoteAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + + return $this->parseAddress(\stream_socket_get_name($this->stream, true)); + } + + public function getLocalAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + + return $this->parseAddress(\stream_socket_get_name($this->stream, false)); + } + + private function parseAddress($address) + { + if ($address === false) { + return null; + } + + if ($this->unix) { + // remove trailing colon from address for HHVM < 3.19: https://3v4l.org/5C1lo + // note that technically ":" is a valid address, so keep this in place otherwise + if (\substr($address, -1) === ':' && \defined('HHVM_VERSION_ID') && \HHVM_VERSION_ID < 31900) { + $address = (string)\substr($address, 0, -1); // @codeCoverageIgnore + } + + // work around unknown addresses should return null value: https://3v4l.org/5C1lo and https://bugs.php.net/bug.php?id=74556 + // PHP uses "\0" string and HHVM uses empty string (colon removed above) + if ($address === '' || $address[0] === "\x00" ) { + return null; // @codeCoverageIgnore + } + + return 'unix://' . $address; + } + + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore + } + + return ($this->encryptionEnabled ? 'tls' : 'tcp') . '://' . $address; + } +} diff --git a/trilhas_poo/vendor/react/socket/src/ConnectionInterface.php b/trilhas_poo/vendor/react/socket/src/ConnectionInterface.php new file mode 100644 index 0000000..64613b5 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/ConnectionInterface.php @@ -0,0 +1,119 @@ +on('data', function ($chunk) { + * echo $chunk; + * }); + * + * $connection->on('end', function () { + * echo 'ended'; + * }); + * + * $connection->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage(); + * }); + * + * $connection->on('close', function () { + * echo 'closed'; + * }); + * + * $connection->write($data); + * $connection->end($data = null); + * $connection->close(); + * // … + * ``` + * + * For more details, see the + * [`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + * + * @see DuplexStreamInterface + * @see ServerInterface + * @see ConnectorInterface + */ +interface ConnectionInterface extends DuplexStreamInterface +{ + /** + * Returns the full remote address (URI) where this connection has been established with + * + * ```php + * $address = $connection->getRemoteAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the remote address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based connection and you only want the remote IP, you may + * use something like this: + * + * ```php + * $address = $connection->getRemoteAddress(); + * $ip = trim(parse_url($address, PHP_URL_HOST), '[]'); + * echo 'Connection with ' . $ip . PHP_EOL; + * ``` + * + * @return ?string remote address (URI) or null if unknown + */ + public function getRemoteAddress(); + + /** + * Returns the full local address (full URI with scheme, IP and port) where this connection has been established with + * + * ```php + * $address = $connection->getLocalAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the local address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * This method complements the [`getRemoteAddress()`](#getremoteaddress) method, + * so they should not be confused. + * + * If your `TcpServer` instance is listening on multiple interfaces (e.g. using + * the address `0.0.0.0`), you can use this method to find out which interface + * actually accepted this connection (such as a public or local interface). + * + * If your system has multiple interfaces (e.g. a WAN and a LAN interface), + * you can use this method to find out which interface was actually + * used for this connection. + * + * @return ?string local address (URI) or null if unknown + * @see self::getRemoteAddress() + */ + public function getLocalAddress(); +} diff --git a/trilhas_poo/vendor/react/socket/src/Connector.php b/trilhas_poo/vendor/react/socket/src/Connector.php new file mode 100644 index 0000000..15faa46 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/Connector.php @@ -0,0 +1,236 @@ + true, + 'tls' => true, + 'unix' => true, + + 'dns' => true, + 'timeout' => true, + 'happy_eyeballs' => true, + ); + + if ($context['timeout'] === true) { + $context['timeout'] = (float)\ini_get("default_socket_timeout"); + } + + if ($context['tcp'] instanceof ConnectorInterface) { + $tcp = $context['tcp']; + } else { + $tcp = new TcpConnector( + $loop, + \is_array($context['tcp']) ? $context['tcp'] : array() + ); + } + + if ($context['dns'] !== false) { + if ($context['dns'] instanceof ResolverInterface) { + $resolver = $context['dns']; + } else { + if ($context['dns'] !== true) { + $config = $context['dns']; + } else { + // try to load nameservers from system config or default to Google's public DNS + $config = DnsConfig::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; // @codeCoverageIgnore + } + } + + $factory = new DnsFactory(); + $resolver = $factory->createCached( + $config, + $loop + ); + } + + if ($context['happy_eyeballs'] === true) { + $tcp = new HappyEyeBallsConnector($loop, $tcp, $resolver); + } else { + $tcp = new DnsConnector($tcp, $resolver); + } + } + + if ($context['tcp'] !== false) { + $context['tcp'] = $tcp; + + if ($context['timeout'] !== false) { + $context['tcp'] = new TimeoutConnector( + $context['tcp'], + $context['timeout'], + $loop + ); + } + + $this->connectors['tcp'] = $context['tcp']; + } + + if ($context['tls'] !== false) { + if (!$context['tls'] instanceof ConnectorInterface) { + $context['tls'] = new SecureConnector( + $tcp, + $loop, + \is_array($context['tls']) ? $context['tls'] : array() + ); + } + + if ($context['timeout'] !== false) { + $context['tls'] = new TimeoutConnector( + $context['tls'], + $context['timeout'], + $loop + ); + } + + $this->connectors['tls'] = $context['tls']; + } + + if ($context['unix'] !== false) { + if (!$context['unix'] instanceof ConnectorInterface) { + $context['unix'] = new UnixConnector($loop); + } + $this->connectors['unix'] = $context['unix']; + } + } + + public function connect($uri) + { + $scheme = 'tcp'; + if (\strpos($uri, '://') !== false) { + $scheme = (string)\substr($uri, 0, \strpos($uri, '://')); + } + + if (!isset($this->connectors[$scheme])) { + return \React\Promise\reject(new \RuntimeException( + 'No connector available for URI scheme "' . $scheme . '" (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + return $this->connectors[$scheme]->connect($uri); + } + + + /** + * [internal] Builds on URI from the given URI parts and ip address with original hostname as query + * + * @param array $parts + * @param string $host + * @param string $ip + * @return string + * @internal + */ + public static function uri(array $parts, $host, $ip) + { + $uri = ''; + + // prepend original scheme if known + if (isset($parts['scheme'])) { + $uri .= $parts['scheme'] . '://'; + } + + if (\strpos($ip, ':') !== false) { + // enclose IPv6 addresses in square brackets before appending port + $uri .= '[' . $ip . ']'; + } else { + $uri .= $ip; + } + + // append original port if known + if (isset($parts['port'])) { + $uri .= ':' . $parts['port']; + } + + // append orignal path if known + if (isset($parts['path'])) { + $uri .= $parts['path']; + } + + // append original query if known + if (isset($parts['query'])) { + $uri .= '?' . $parts['query']; + } + + // append original hostname as query if resolved via DNS and if + // destination URI does not contain "hostname" query param already + $args = array(); + \parse_str(isset($parts['query']) ? $parts['query'] : '', $args); + if ($host !== $ip && !isset($args['hostname'])) { + $uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host); + } + + // append original fragment if known + if (isset($parts['fragment'])) { + $uri .= '#' . $parts['fragment']; + } + + return $uri; + } +} diff --git a/trilhas_poo/vendor/react/socket/src/ConnectorInterface.php b/trilhas_poo/vendor/react/socket/src/ConnectorInterface.php new file mode 100644 index 0000000..1f07b75 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/ConnectorInterface.php @@ -0,0 +1,59 @@ +connect('google.com:443')->then( + * function (React\Socket\ConnectionInterface $connection) { + * // connection successfully established + * }, + * function (Exception $error) { + * // failed to connect due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $connector->connect($uri); + * + * $promise->cancel(); + * ``` + * + * @param string $uri + * @return \React\Promise\PromiseInterface + * Resolves with a `ConnectionInterface` on success or rejects with an `Exception` on error. + * @see ConnectionInterface + */ + public function connect($uri); +} diff --git a/trilhas_poo/vendor/react/socket/src/DnsConnector.php b/trilhas_poo/vendor/react/socket/src/DnsConnector.php new file mode 100644 index 0000000..e5fd238 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/DnsConnector.php @@ -0,0 +1,119 @@ +connector = $connector; + $this->resolver = $resolver; + } + + public function connect($uri) + { + $original = $uri; + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + $parts = \parse_url($uri); + if (isset($parts['scheme'])) { + unset($parts['scheme']); + } + } else { + $parts = \parse_url($uri); + } + + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $original . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + $host = \trim($parts['host'], '[]'); + $connector = $this->connector; + + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (@\inet_pton($host) !== false) { + return $connector->connect($original); + } + + $promise = $this->resolver->resolve($host); + $resolved = null; + + return new Promise\Promise( + function ($resolve, $reject) use (&$promise, &$resolved, $uri, $connector, $host, $parts) { + // resolve/reject with result of DNS lookup + $promise->then(function ($ip) use (&$promise, &$resolved, $uri, $connector, $host, $parts) { + $resolved = $ip; + + return $promise = $connector->connect( + Connector::uri($parts, $host, $ip) + )->then(null, function (\Exception $e) use ($uri) { + if ($e instanceof \RuntimeException) { + $message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage()); + $e = new \RuntimeException( + 'Connection to ' . $uri . ' failed: ' . $message, + $e->getCode(), + $e + ); + + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + if (\PHP_VERSION_ID < 80100) { + $r->setAccessible(true); + } + $trace = $r->getValue($e); + + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } + + throw $e; + }); + }, function ($e) use ($uri, $reject) { + $reject(new \RuntimeException('Connection to ' . $uri .' failed during DNS lookup: ' . $e->getMessage(), 0, $e)); + })->then($resolve, $reject); + }, + function ($_, $reject) use (&$promise, &$resolved, $uri) { + // cancellation should reject connection attempt + // reject DNS resolution with custom reason, otherwise rely on connection cancellation below + if ($resolved === null) { + $reject(new \RuntimeException( + 'Connection to ' . $uri . ' cancelled during DNS lookup (ECONNABORTED)', + \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103 + )); + } + + // (try to) cancel pending DNS lookup / connection attempt + if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $_ = $reject = null; + + $promise->cancel(); + $promise = null; + } + } + ); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/FdServer.php b/trilhas_poo/vendor/react/socket/src/FdServer.php new file mode 100644 index 0000000..8e46719 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/FdServer.php @@ -0,0 +1,222 @@ +on('connection', function (ConnectionInterface $connection) { + * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + * @internal + */ +final class FdServer extends EventEmitter implements ServerInterface +{ + private $master; + private $loop; + private $unix = false; + private $listening = false; + + /** + * Creates a socket server and starts listening on the given file descriptor + * + * This starts accepting new incoming connections on the given file descriptor. + * See also the `connection event` documented in the `ServerInterface` + * for more details. + * + * ```php + * $socket = new React\Socket\FdServer(3); + * ``` + * + * If the given FD is invalid or out of range, it will throw an `InvalidArgumentException`: + * + * ```php + * // throws InvalidArgumentException + * $socket = new React\Socket\FdServer(-1); + * ``` + * + * If the given FD appears to be valid, but listening on it fails (such as + * if the FD does not exist or does not refer to a socket server), it will + * throw a `RuntimeException`: + * + * ```php + * // throws RuntimeException because FD does not reference a socket server + * $socket = new React\Socket\FdServer(0, $loop); + * ``` + * + * Note that these error conditions may vary depending on your system and/or + * configuration. + * See the exception message and code for more details about the actual error + * condition. + * + * @param int|string $fd FD number such as `3` or as URL in the form of `php://fd/3` + * @param ?LoopInterface $loop + * @throws \InvalidArgumentException if the listening address is invalid + * @throws \RuntimeException if listening on this address fails (already in use etc.) + */ + public function __construct($fd, $loop = null) + { + if (\preg_match('#^php://fd/(\d+)$#', $fd, $m)) { + $fd = (int) $m[1]; + } + if (!\is_int($fd) || $fd < 0 || $fd >= \PHP_INT_MAX) { + throw new \InvalidArgumentException( + 'Invalid FD number given (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + ); + } + + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + $this->loop = $loop ?: Loop::get(); + + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fopen(php://fd/3): Failed to open stream: Error duping file descriptor 3; possibly it doesn't exist: [9]: Bad file descriptor + \preg_match('/\[(\d+)\]: (.*)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + + $this->master = \fopen('php://fd/' . $fd, 'r+'); + + \restore_error_handler(); + + if (false === $this->master) { + throw new \RuntimeException( + 'Failed to listen on FD ' . $fd . ': ' . $errstr . SocketServer::errconst($errno), + $errno + ); + } + + $meta = \stream_get_meta_data($this->master); + if (!isset($meta['stream_type']) || $meta['stream_type'] !== 'tcp_socket') { + \fclose($this->master); + + $errno = \defined('SOCKET_ENOTSOCK') ? \SOCKET_ENOTSOCK : 88; + $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Not a socket'; + + throw new \RuntimeException( + 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (ENOTSOCK)', + $errno + ); + } + + // Socket should not have a peer address if this is a listening socket. + // Looks like this work-around is the closest we can get because PHP doesn't expose SO_ACCEPTCONN even with ext-sockets. + if (\stream_socket_get_name($this->master, true) !== false) { + \fclose($this->master); + + $errno = \defined('SOCKET_EISCONN') ? \SOCKET_EISCONN : 106; + $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Socket is connected'; + + throw new \RuntimeException( + 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (EISCONN)', + $errno + ); + } + + // Assume this is a Unix domain socket (UDS) when its listening address doesn't parse as a valid URL with a port. + // Looks like this work-around is the closest we can get because PHP doesn't expose SO_DOMAIN even with ext-sockets. + $this->unix = \parse_url($this->getAddress(), \PHP_URL_PORT) === false; + + \stream_set_blocking($this->master, false); + + $this->resume(); + } + + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + + $address = \stream_socket_get_name($this->master, false); + + if ($this->unix === true) { + return 'unix://' . $address; + } + + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore + } + + return 'tcp://' . $address; + } + + public function pause() + { + if (!$this->listening) { + return; + } + + $this->loop->removeReadStream($this->master); + $this->listening = false; + } + + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use ($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = true; + } + + public function close() + { + if (!\is_resource($this->master)) { + return; + } + + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleConnection($socket) + { + $connection = new Connection($socket, $this->loop); + $connection->unix = $this->unix; + + $this->emit('connection', array($connection)); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/FixedUriConnector.php b/trilhas_poo/vendor/react/socket/src/FixedUriConnector.php new file mode 100644 index 0000000..f83241d --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/FixedUriConnector.php @@ -0,0 +1,41 @@ +connect('localhost:80'); + * ``` + */ +class FixedUriConnector implements ConnectorInterface +{ + private $uri; + private $connector; + + /** + * @param string $uri + * @param ConnectorInterface $connector + */ + public function __construct($uri, ConnectorInterface $connector) + { + $this->uri = $uri; + $this->connector = $connector; + } + + public function connect($_) + { + return $this->connector->connect($this->uri); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php b/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php new file mode 100644 index 0000000..d4f05e8 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php @@ -0,0 +1,334 @@ + false, + Message::TYPE_AAAA => false, + ); + public $resolverPromises = array(); + public $connectionPromises = array(); + public $connectQueue = array(); + public $nextAttemptTimer; + public $parts; + public $ipsCount = 0; + public $failureCount = 0; + public $resolve; + public $reject; + + public $lastErrorFamily; + public $lastError6; + public $lastError4; + + public function __construct(LoopInterface $loop, ConnectorInterface $connector, ResolverInterface $resolver, $uri, $host, $parts) + { + $this->loop = $loop; + $this->connector = $connector; + $this->resolver = $resolver; + $this->uri = $uri; + $this->host = $host; + $this->parts = $parts; + } + + public function connect() + { + $that = $this; + return new Promise\Promise(function ($resolve, $reject) use ($that) { + $lookupResolve = function ($type) use ($that, $resolve, $reject) { + return function (array $ips) use ($that, $type, $resolve, $reject) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = true; + + $that->mixIpsIntoConnectQueue($ips); + + // start next connection attempt if not already awaiting next + if ($that->nextAttemptTimer === null && $that->connectQueue) { + $that->check($resolve, $reject); + } + }; + }; + + $that->resolverPromises[Message::TYPE_AAAA] = $that->resolve(Message::TYPE_AAAA, $reject)->then($lookupResolve(Message::TYPE_AAAA)); + $that->resolverPromises[Message::TYPE_A] = $that->resolve(Message::TYPE_A, $reject)->then(function (array $ips) use ($that) { + // happy path: IPv6 has resolved already (or could not resolve), continue with IPv4 addresses + if ($that->resolved[Message::TYPE_AAAA] === true || !$ips) { + return $ips; + } + + // Otherwise delay processing IPv4 lookup until short timer passes or IPv6 resolves in the meantime + $deferred = new Promise\Deferred(function () use (&$ips) { + // discard all IPv4 addresses if cancelled + $ips = array(); + }); + $timer = $that->loop->addTimer($that::RESOLUTION_DELAY, function () use ($deferred, $ips) { + $deferred->resolve($ips); + }); + + $that->resolverPromises[Message::TYPE_AAAA]->then(function () use ($that, $timer, $deferred, &$ips) { + $that->loop->cancelTimer($timer); + $deferred->resolve($ips); + }); + + return $deferred->promise(); + })->then($lookupResolve(Message::TYPE_A)); + }, function ($_, $reject) use ($that) { + $reject(new \RuntimeException( + 'Connection to ' . $that->uri . ' cancelled' . (!$that->connectionPromises ? ' during DNS lookup' : '') . ' (ECONNABORTED)', + \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103 + )); + $_ = $reject = null; + + $that->cleanUp(); + }); + } + + /** + * @internal + * @param int $type DNS query type + * @param callable $reject + * @return \React\Promise\PromiseInterface Returns a promise that + * always resolves with a list of IP addresses on success or an empty + * list on error. + */ + public function resolve($type, $reject) + { + $that = $this; + return $that->resolver->resolveAll($that->host, $type)->then(null, function (\Exception $e) use ($type, $reject, $that) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = true; + + if ($type === Message::TYPE_A) { + $that->lastError4 = $e->getMessage(); + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $e->getMessage(); + $that->lastErrorFamily = 6; + } + + // cancel next attempt timer when there are no more IPs to connect to anymore + if ($that->nextAttemptTimer !== null && !$that->connectQueue) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + + if ($that->hasBeenResolved() && $that->ipsCount === 0) { + $reject(new \RuntimeException( + $that->error(), + 0, + $e + )); + } + + // Exception already handled above, so don't throw an unhandled rejection here + return array(); + }); + } + + /** + * @internal + */ + public function check($resolve, $reject) + { + $ip = \array_shift($this->connectQueue); + + // start connection attempt and remember array position to later unset again + $this->connectionPromises[] = $this->attemptConnection($ip); + \end($this->connectionPromises); + $index = \key($this->connectionPromises); + + $that = $this; + $that->connectionPromises[$index]->then(function ($connection) use ($that, $index, $resolve) { + unset($that->connectionPromises[$index]); + + $that->cleanUp(); + + $resolve($connection); + }, function (\Exception $e) use ($that, $index, $ip, $resolve, $reject) { + unset($that->connectionPromises[$index]); + + $that->failureCount++; + + $message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage()); + if (\strpos($ip, ':') === false) { + $that->lastError4 = $message; + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $message; + $that->lastErrorFamily = 6; + } + + // start next connection attempt immediately on error + if ($that->connectQueue) { + if ($that->nextAttemptTimer !== null) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + + $that->check($resolve, $reject); + } + + if ($that->hasBeenResolved() === false) { + return; + } + + if ($that->ipsCount === $that->failureCount) { + $that->cleanUp(); + + $reject(new \RuntimeException( + $that->error(), + $e->getCode(), + $e + )); + } + }); + + // Allow next connection attempt in 100ms: https://tools.ietf.org/html/rfc8305#section-5 + // Only start timer when more IPs are queued or when DNS query is still pending (might add more IPs) + if ($this->nextAttemptTimer === null && (\count($this->connectQueue) > 0 || $this->resolved[Message::TYPE_A] === false || $this->resolved[Message::TYPE_AAAA] === false)) { + $this->nextAttemptTimer = $this->loop->addTimer(self::CONNECTION_ATTEMPT_DELAY, function () use ($that, $resolve, $reject) { + $that->nextAttemptTimer = null; + + if ($that->connectQueue) { + $that->check($resolve, $reject); + } + }); + } + } + + /** + * @internal + */ + public function attemptConnection($ip) + { + $uri = Connector::uri($this->parts, $this->host, $ip); + + return $this->connector->connect($uri); + } + + /** + * @internal + */ + public function cleanUp() + { + // clear list of outstanding IPs to avoid creating new connections + $this->connectQueue = array(); + + // cancel pending connection attempts + foreach ($this->connectionPromises as $connectionPromise) { + if ($connectionPromise instanceof PromiseInterface && \method_exists($connectionPromise, 'cancel')) { + $connectionPromise->cancel(); + } + } + + // cancel pending DNS resolution (cancel IPv4 first in case it is awaiting IPv6 resolution delay) + foreach (\array_reverse($this->resolverPromises) as $resolverPromise) { + if ($resolverPromise instanceof PromiseInterface && \method_exists($resolverPromise, 'cancel')) { + $resolverPromise->cancel(); + } + } + + if ($this->nextAttemptTimer instanceof TimerInterface) { + $this->loop->cancelTimer($this->nextAttemptTimer); + $this->nextAttemptTimer = null; + } + } + + /** + * @internal + */ + public function hasBeenResolved() + { + foreach ($this->resolved as $typeHasBeenResolved) { + if ($typeHasBeenResolved === false) { + return false; + } + } + + return true; + } + + /** + * Mixes an array of IP addresses into the connect queue in such a way they alternate when attempting to connect. + * The goal behind it is first attempt to connect to IPv6, then to IPv4, then to IPv6 again until one of those + * attempts succeeds. + * + * @link https://tools.ietf.org/html/rfc8305#section-4 + * + * @internal + */ + public function mixIpsIntoConnectQueue(array $ips) + { + \shuffle($ips); + $this->ipsCount += \count($ips); + $connectQueueStash = $this->connectQueue; + $this->connectQueue = array(); + while (\count($connectQueueStash) > 0 || \count($ips) > 0) { + if (\count($ips) > 0) { + $this->connectQueue[] = \array_shift($ips); + } + if (\count($connectQueueStash) > 0) { + $this->connectQueue[] = \array_shift($connectQueueStash); + } + } + } + + /** + * @internal + * @return string + */ + public function error() + { + if ($this->lastError4 === $this->lastError6) { + $message = $this->lastError6; + } elseif ($this->lastErrorFamily === 6) { + $message = 'Last error for IPv6: ' . $this->lastError6 . '. Previous error for IPv4: ' . $this->lastError4; + } else { + $message = 'Last error for IPv4: ' . $this->lastError4 . '. Previous error for IPv6: ' . $this->lastError6; + } + + if ($this->hasBeenResolved() && $this->ipsCount === 0) { + if ($this->lastError6 === $this->lastError4) { + $message = ' during DNS lookup: ' . $this->lastError6; + } else { + $message = ' during DNS lookup. ' . $message; + } + } else { + $message = ': ' . $message; + } + + return 'Connection to ' . $this->uri . ' failed' . $message; + } +} diff --git a/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnector.php b/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnector.php new file mode 100644 index 0000000..a5511ac --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/HappyEyeBallsConnector.php @@ -0,0 +1,80 @@ +loop = $loop ?: Loop::get(); + $this->connector = $connector; + $this->resolver = $resolver; + } + + public function connect($uri) + { + $original = $uri; + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + $parts = \parse_url($uri); + if (isset($parts['scheme'])) { + unset($parts['scheme']); + } + } else { + $parts = \parse_url($uri); + } + + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $original . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + $host = \trim($parts['host'], '[]'); + + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (@\inet_pton($host) !== false) { + return $this->connector->connect($original); + } + + $builder = new HappyEyeBallsConnectionBuilder( + $this->loop, + $this->connector, + $this->resolver, + $uri, + $host, + $parts + ); + return $builder->connect(); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/LimitingServer.php b/trilhas_poo/vendor/react/socket/src/LimitingServer.php new file mode 100644 index 0000000..d19000b --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/LimitingServer.php @@ -0,0 +1,203 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +class LimitingServer extends EventEmitter implements ServerInterface +{ + private $connections = array(); + private $server; + private $limit; + + private $pauseOnLimit = false; + private $autoPaused = false; + private $manuPaused = false; + + /** + * Instantiates a new LimitingServer. + * + * You have to pass a maximum number of open connections to ensure + * the server will automatically reject (close) connections once this limit + * is exceeded. In this case, it will emit an `error` event to inform about + * this and no `connection` event will be emitted. + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * You MAY pass a `null` limit in order to put no limit on the number of + * open connections and keep accepting new connection until you run out of + * operating system resources (such as open file handles). This may be + * useful if you do not want to take care of applying a limit but still want + * to use the `getConnections()` method. + * + * You can optionally configure the server to pause accepting new + * connections once the connection limit is reached. In this case, it will + * pause the underlying server and no longer process any new connections at + * all, thus also no longer closing any excessive connections. + * The underlying operating system is responsible for keeping a backlog of + * pending connections until its limit is reached, at which point it will + * start rejecting further connections. + * Once the server is below the connection limit, it will continue consuming + * connections from the backlog and will process any outstanding data on + * each connection. + * This mode may be useful for some protocols that are designed to wait for + * a response message (such as HTTP), but may be less useful for other + * protocols that demand immediate responses (such as a "welcome" message in + * an interactive chat). + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100, true); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * @param ServerInterface $server + * @param int|null $connectionLimit + * @param bool $pauseOnLimit + */ + public function __construct(ServerInterface $server, $connectionLimit, $pauseOnLimit = false) + { + $this->server = $server; + $this->limit = $connectionLimit; + if ($connectionLimit !== null) { + $this->pauseOnLimit = $pauseOnLimit; + } + + $this->server->on('connection', array($this, 'handleConnection')); + $this->server->on('error', array($this, 'handleError')); + } + + /** + * Returns an array with all currently active connections + * + * ```php + * foreach ($server->getConnection() as $connection) { + * $connection->write('Hi!'); + * } + * ``` + * + * @return ConnectionInterface[] + */ + public function getConnections() + { + return $this->connections; + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + if (!$this->manuPaused) { + $this->manuPaused = true; + + if (!$this->autoPaused) { + $this->server->pause(); + } + } + } + + public function resume() + { + if ($this->manuPaused) { + $this->manuPaused = false; + + if (!$this->autoPaused) { + $this->server->resume(); + } + } + } + + public function close() + { + $this->server->close(); + } + + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + // close connection if limit exceeded + if ($this->limit !== null && \count($this->connections) >= $this->limit) { + $this->handleError(new \OverflowException('Connection closed because server reached connection limit')); + $connection->close(); + return; + } + + $this->connections[] = $connection; + $that = $this; + $connection->on('close', function () use ($that, $connection) { + $that->handleDisconnection($connection); + }); + + // pause accepting new connections if limit exceeded + if ($this->pauseOnLimit && !$this->autoPaused && \count($this->connections) >= $this->limit) { + $this->autoPaused = true; + + if (!$this->manuPaused) { + $this->server->pause(); + } + } + + $this->emit('connection', array($connection)); + } + + /** @internal */ + public function handleDisconnection(ConnectionInterface $connection) + { + unset($this->connections[\array_search($connection, $this->connections)]); + + // continue accepting new connection if below limit + if ($this->autoPaused && \count($this->connections) < $this->limit) { + $this->autoPaused = false; + + if (!$this->manuPaused) { + $this->server->resume(); + } + } + } + + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/SecureConnector.php b/trilhas_poo/vendor/react/socket/src/SecureConnector.php new file mode 100644 index 0000000..98cc46a --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/SecureConnector.php @@ -0,0 +1,134 @@ +connector = $connector; + $this->streamEncryption = new StreamEncryption($loop ?: Loop::get(), false); + $this->context = $context; + } + + public function connect($uri) + { + if (!\function_exists('stream_socket_enable_crypto')) { + return Promise\reject(new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)')); // @codeCoverageIgnore + } + + if (\strpos($uri, '://') === false) { + $uri = 'tls://' . $uri; + } + + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme']) || $parts['scheme'] !== 'tls') { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $uri . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + $context = $this->context; + $encryption = $this->streamEncryption; + $connected = false; + /** @var \React\Promise\PromiseInterface $promise */ + $promise = $this->connector->connect( + \str_replace('tls://', '', $uri) + )->then(function (ConnectionInterface $connection) use ($context, $encryption, $uri, &$promise, &$connected) { + // (unencrypted) TCP/IP connection succeeded + $connected = true; + + if (!$connection instanceof Connection) { + $connection->close(); + throw new \UnexpectedValueException('Base connector does not use internal Connection class exposing stream resource'); + } + + // set required SSL/TLS context options + foreach ($context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + + // try to enable encryption + return $promise = $encryption->enable($connection)->then(null, function ($error) use ($connection, $uri) { + // establishing encryption failed => close invalid connection and return error + $connection->close(); + + throw new \RuntimeException( + 'Connection to ' . $uri . ' failed during TLS handshake: ' . $error->getMessage(), + $error->getCode() + ); + }); + }, function (\Exception $e) use ($uri) { + if ($e instanceof \RuntimeException) { + $message = \preg_replace('/^Connection to [^ ]+/', '', $e->getMessage()); + $e = new \RuntimeException( + 'Connection to ' . $uri . $message, + $e->getCode(), + $e + ); + + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + if (\PHP_VERSION_ID < 80100) { + $r->setAccessible(true); + } + $trace = $r->getValue($e); + + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } + + throw $e; + }); + + return new \React\Promise\Promise( + function ($resolve, $reject) use ($promise) { + $promise->then($resolve, $reject); + }, + function ($_, $reject) use (&$promise, $uri, &$connected) { + if ($connected) { + $reject(new \RuntimeException( + 'Connection to ' . $uri . ' cancelled during TLS handshake (ECONNABORTED)', + \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103 + )); + } + + $promise->cancel(); + $promise = null; + } + ); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/SecureServer.php b/trilhas_poo/vendor/react/socket/src/SecureServer.php new file mode 100644 index 0000000..5a202d2 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/SecureServer.php @@ -0,0 +1,210 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + * + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * Whenever a client fails to perform a successful TLS handshake, it will emit an + * `error` event and then close the underlying TCP/IP connection: + * + * ```php + * $server->on('error', function (Exception $e) { + * echo 'Error' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * Note that the `SecureServer` class is a concrete implementation for TLS sockets. + * If you want to typehint in your higher-level protocol implementation, you SHOULD + * use the generic `ServerInterface` instead. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class SecureServer extends EventEmitter implements ServerInterface +{ + private $tcp; + private $encryption; + private $context; + + /** + * Creates a secure TLS server and starts waiting for incoming connections + * + * It does so by wrapping a `TcpServer` instance which waits for plaintext + * TCP/IP connections and then performs a TLS handshake for each connection. + * It thus requires valid [TLS context options], + * which in its most basic form may look something like this if you're using a + * PEM encoded certificate file: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem' + * )); + * ``` + * + * Note that the certificate file will not be loaded on instantiation but when an + * incoming connection initializes its TLS context. + * This implies that any invalid certificate file paths or contents will only cause + * an `error` event at a later time. + * + * If your private key is encrypted with a passphrase, you have to specify it + * like this: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem', + * 'passphrase' => 'secret' + * )); + * ``` + * + * Note that available [TLS context options], + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Advanced usage: Despite allowing any `ServerInterface` as first parameter, + * you SHOULD pass a `TcpServer` instance as first parameter, unless you + * know what you're doing. + * Internally, the `SecureServer` has to set the required TLS context options on + * the underlying stream resources. + * These resources are not exposed through any of the interfaces defined in this + * package, but only through the internal `Connection` class. + * The `TcpServer` class is guaranteed to emit connections that implement + * the `ConnectionInterface` and uses the internal `Connection` class in order to + * expose these underlying resources. + * If you use a custom `ServerInterface` and its `connection` event does not + * meet this requirement, the `SecureServer` will emit an `error` event and + * then close the underlying connection. + * + * @param ServerInterface|TcpServer $tcp + * @param ?LoopInterface $loop + * @param array $context + * @throws BadMethodCallException for legacy HHVM < 3.8 due to lack of support + * @see TcpServer + * @link https://www.php.net/manual/en/context.ssl.php for TLS context options + */ + public function __construct(ServerInterface $tcp, $loop = null, array $context = array()) + { + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + if (!\function_exists('stream_socket_enable_crypto')) { + throw new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)'); // @codeCoverageIgnore + } + + // default to empty passphrase to suppress blocking passphrase prompt + $context += array( + 'passphrase' => '' + ); + + $this->tcp = $tcp; + $this->encryption = new StreamEncryption($loop ?: Loop::get()); + $this->context = $context; + + $that = $this; + $this->tcp->on('connection', function ($connection) use ($that) { + $that->handleConnection($connection); + }); + $this->tcp->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + $address = $this->tcp->getAddress(); + if ($address === null) { + return null; + } + + return \str_replace('tcp://' , 'tls://', $address); + } + + public function pause() + { + $this->tcp->pause(); + } + + public function resume() + { + $this->tcp->resume(); + } + + public function close() + { + return $this->tcp->close(); + } + + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + if (!$connection instanceof Connection) { + $this->emit('error', array(new \UnexpectedValueException('Base server does not use internal Connection class exposing stream resource'))); + $connection->close(); + return; + } + + foreach ($this->context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + + // get remote address before starting TLS handshake in case connection closes during handshake + $remote = $connection->getRemoteAddress(); + $that = $this; + + $this->encryption->enable($connection)->then( + function ($conn) use ($that) { + $that->emit('connection', array($conn)); + }, + function ($error) use ($that, $connection, $remote) { + $error = new \RuntimeException( + 'Connection from ' . $remote . ' failed during TLS handshake: ' . $error->getMessage(), + $error->getCode() + ); + + $that->emit('error', array($error)); + $connection->close(); + } + ); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/Server.php b/trilhas_poo/vendor/react/socket/src/Server.php new file mode 100644 index 0000000..b24c556 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/Server.php @@ -0,0 +1,118 @@ + $context); + } + + // apply default options if not explicitly given + $context += array( + 'tcp' => array(), + 'tls' => array(), + 'unix' => array() + ); + + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== false) { + $scheme = \substr($uri, 0, $pos); + } + + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } else { + $server = new TcpServer(str_replace('tls://', '', $uri), $loop, $context['tcp']); + + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + + $this->server = $server; + + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use ($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (Exception $error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + $this->server->pause(); + } + + public function resume() + { + $this->server->resume(); + } + + public function close() + { + $this->server->close(); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/ServerInterface.php b/trilhas_poo/vendor/react/socket/src/ServerInterface.php new file mode 100644 index 0000000..aa79fa1 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/ServerInterface.php @@ -0,0 +1,151 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'new connection' . PHP_EOL; + * }); + * ``` + * + * See also the `ConnectionInterface` for more details about handling the + * incoming connection. + * + * error event: + * The `error` event will be emitted whenever there's an error accepting a new + * connection from a client. + * + * ```php + * $socket->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * Note that this is not a fatal error event, i.e. the server keeps listening for + * new connections even after this event. + * + * @see ConnectionInterface + */ +interface ServerInterface extends EventEmitterInterface +{ + /** + * Returns the full address (URI) this server is currently listening on + * + * ```php + * $address = $socket->getAddress(); + * echo 'Server listening on ' . $address . PHP_EOL; + * ``` + * + * If the address can not be determined or is unknown at this time (such as + * after the socket has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80` or `tls://127.0.0.1:443`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based server and you only want the local port, you may + * use something like this: + * + * ```php + * $address = $socket->getAddress(); + * $port = parse_url($address, PHP_URL_PORT); + * echo 'Server listening on port ' . $port . PHP_EOL; + * ``` + * + * @return ?string the full listening address (URI) or NULL if it is unknown (not applicable to this server socket or already closed) + */ + public function getAddress(); + + /** + * Pauses accepting new incoming connections. + * + * Removes the socket resource from the EventLoop and thus stop accepting + * new connections. Note that the listening socket stays active and is not + * closed. + * + * This means that new incoming connections will stay pending in the + * operating system backlog until its configurable backlog is filled. + * Once the backlog is filled, the operating system may reject further + * incoming connections until the backlog is drained again by resuming + * to accept new connections. + * + * Once the server is paused, no futher `connection` events SHOULD + * be emitted. + * + * ```php + * $socket->pause(); + * + * $socket->on('connection', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * server MAY continue emitting `connection` events. + * + * Unless otherwise noted, a successfully opened server SHOULD NOT start + * in paused state. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::resume() + * @return void + */ + public function pause(); + + /** + * Resumes accepting new incoming connections. + * + * Re-attach the socket resource to the EventLoop after a previous `pause()`. + * + * ```php + * $socket->pause(); + * + * Loop::addTimer(1.0, function () use ($socket) { + * $socket->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::pause() + * @return void + */ + public function resume(); + + /** + * Shuts down this listening socket + * + * This will stop listening for new incoming connections on this socket. + * + * Calling this method more than once on the same instance is a NO-OP. + * + * @return void + */ + public function close(); +} diff --git a/trilhas_poo/vendor/react/socket/src/SocketServer.php b/trilhas_poo/vendor/react/socket/src/SocketServer.php new file mode 100644 index 0000000..e987f5f --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/SocketServer.php @@ -0,0 +1,215 @@ + array(), + 'tls' => array(), + 'unix' => array() + ); + + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== false) { + $scheme = \substr($uri, 0, $pos); + } + + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } elseif ($scheme === 'php') { + $server = new FdServer($uri, $loop); + } else { + if (preg_match('#^(?:\w+://)?\d+$#', $uri)) { + throw new \InvalidArgumentException( + 'Invalid URI given (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + ); + } + + $server = new TcpServer(str_replace('tls://', '', $uri), $loop, $context['tcp']); + + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + + $this->server = $server; + + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use ($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (\Exception $error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + $this->server->pause(); + } + + public function resume() + { + $this->server->resume(); + } + + public function close() + { + $this->server->close(); + } + + /** + * [internal] Internal helper method to accept new connection from given server socket + * + * @param resource $socket server socket to accept connection from + * @return resource new client socket if any + * @throws \RuntimeException if accepting fails + * @internal + */ + public static function accept($socket) + { + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // stream_socket_accept(): accept failed: Connection timed out + $errstr = \preg_replace('#.*: #', '', $error); + $errno = SocketServer::errno($errstr); + }); + + $newSocket = \stream_socket_accept($socket, 0); + + \restore_error_handler(); + + if (false === $newSocket) { + throw new \RuntimeException( + 'Unable to accept new connection: ' . $errstr . self::errconst($errno), + $errno + ); + } + + return $newSocket; + } + + /** + * [Internal] Returns errno value for given errstr + * + * The errno and errstr values describes the type of error that has been + * encountered. This method tries to look up the given errstr and find a + * matching errno value which can be useful to provide more context to error + * messages. It goes through the list of known errno constants when either + * `ext-sockets`, `ext-posix` or `ext-pcntl` is available to find an errno + * matching the given errstr. + * + * @param string $errstr + * @return int errno value (e.g. value of `SOCKET_ECONNREFUSED`) or 0 if not found + * @internal + * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission + * @codeCoverageIgnore + */ + public static function errno($errstr) + { + // PHP defines the required `strerror()` function through either `ext-sockets`, `ext-posix` or `ext-pcntl` + $strerror = \function_exists('socket_strerror') ? 'socket_strerror' : (\function_exists('posix_strerror') ? 'posix_strerror' : (\function_exists('pcntl_strerror') ? 'pcntl_strerror' : null)); + if ($strerror !== null) { + assert(\is_string($strerror) && \is_callable($strerror)); + + // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED` + // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE` + // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errstr` + foreach (\get_defined_constants(false) as $name => $value) { + if (\is_int($value) && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0) && $strerror($value) === $errstr) { + return $value; + } + } + + // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available) + // go through list of all possible errno values from 1 to `MAX_ERRNO` and see if they match the given `$errstr` + for ($errno = 1, $max = \defined('MAX_ERRNO') ? \MAX_ERRNO : 4095; $errno <= $max; ++$errno) { + if ($strerror($errno) === $errstr) { + return $errno; + } + } + } + + // if we reach this, no matching errno value could be found (unlikely when either `ext-sockets`, `ext-posix` or `ext-pcntl` is available) + return 0; + } + + /** + * [Internal] Returns errno constant name for given errno value + * + * The errno value describes the type of error that has been encountered. + * This method tries to look up the given errno value and find a matching + * errno constant name which can be useful to provide more context and more + * descriptive error messages. It goes through the list of known errno + * constants when either `ext-sockets` or `ext-pcntl` is available to find + * the matching errno constant name. + * + * Because this method is used to append more context to error messages, the + * constant name will be prefixed with a space and put between parenthesis + * when found. + * + * @param int $errno + * @return string e.g. ` (ECONNREFUSED)` or empty string if no matching const for the given errno could be found + * @internal + * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission + * @codeCoverageIgnore + */ + public static function errconst($errno) + { + // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED` + // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE` + // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errno` + foreach (\get_defined_constants(false) as $name => $value) { + if ($value === $errno && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0)) { + return ' (' . \substr($name, \strpos($name, '_') + 1) . ')'; + } + } + + // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available) + return ''; + } +} diff --git a/trilhas_poo/vendor/react/socket/src/StreamEncryption.php b/trilhas_poo/vendor/react/socket/src/StreamEncryption.php new file mode 100644 index 0000000..f91a359 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/StreamEncryption.php @@ -0,0 +1,158 @@ +loop = $loop; + $this->server = $server; + + // support TLSv1.0+ by default and exclude legacy SSLv2/SSLv3. + // As of PHP 7.2+ the main crypto method constant includes all TLS versions. + // As of PHP 5.6+ the crypto method is a bitmask, so we explicitly include all TLS versions. + // For legacy PHP < 5.6 the crypto method is a single value only and this constant includes all TLS versions. + // @link https://3v4l.org/9PSST + if ($server) { + $this->method = \STREAM_CRYPTO_METHOD_TLS_SERVER; + + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_2_SERVER; // @codeCoverageIgnore + } + } else { + $this->method = \STREAM_CRYPTO_METHOD_TLS_CLIENT; + + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; // @codeCoverageIgnore + } + } + } + + /** + * @param Connection $stream + * @return \React\Promise\PromiseInterface + */ + public function enable(Connection $stream) + { + return $this->toggle($stream, true); + } + + /** + * @param Connection $stream + * @param bool $toggle + * @return \React\Promise\PromiseInterface + */ + public function toggle(Connection $stream, $toggle) + { + // pause actual stream instance to continue operation on raw stream socket + $stream->pause(); + + // TODO: add write() event to make sure we're not sending any excessive data + + // cancelling this leaves this stream in an inconsistent state… + $deferred = new Deferred(function () { + throw new \RuntimeException(); + }); + + // get actual stream socket from stream instance + $socket = $stream->stream; + + // get crypto method from context options or use global setting from constructor + $method = $this->method; + $context = \stream_context_get_options($socket); + if (isset($context['ssl']['crypto_method'])) { + $method = $context['ssl']['crypto_method']; + } + + $that = $this; + $toggleCrypto = function () use ($socket, $deferred, $toggle, $method, $that) { + $that->toggleCrypto($socket, $deferred, $toggle, $method); + }; + + $this->loop->addReadStream($socket, $toggleCrypto); + + if (!$this->server) { + $toggleCrypto(); + } + + $loop = $this->loop; + + return $deferred->promise()->then(function () use ($stream, $socket, $loop, $toggle) { + $loop->removeReadStream($socket); + + $stream->encryptionEnabled = $toggle; + $stream->resume(); + + return $stream; + }, function($error) use ($stream, $socket, $loop) { + $loop->removeReadStream($socket); + $stream->resume(); + throw $error; + }); + } + + /** + * @internal + * @param resource $socket + * @param Deferred $deferred + * @param bool $toggle + * @param int $method + * @return void + */ + public function toggleCrypto($socket, Deferred $deferred, $toggle, $method) + { + $error = null; + \set_error_handler(function ($_, $errstr) use (&$error) { + $error = \str_replace(array("\r", "\n"), ' ', $errstr); + + // remove useless function name from error message + if (($pos = \strpos($error, "): ")) !== false) { + $error = \substr($error, $pos + 3); + } + }); + + $result = \stream_socket_enable_crypto($socket, $toggle, $method); + + \restore_error_handler(); + + if (true === $result) { + $deferred->resolve(null); + } else if (false === $result) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $d = $deferred; + $deferred = null; + + if (\feof($socket) || $error === null) { + // EOF or failed without error => connection closed during handshake + $d->reject(new \UnexpectedValueException( + 'Connection lost during TLS handshake (ECONNRESET)', + \defined('SOCKET_ECONNRESET') ? \SOCKET_ECONNRESET : 104 + )); + } else { + // handshake failed with error message + $d->reject(new \UnexpectedValueException( + $error + )); + } + } else { + // need more data, will retry + } + } +} diff --git a/trilhas_poo/vendor/react/socket/src/TcpConnector.php b/trilhas_poo/vendor/react/socket/src/TcpConnector.php new file mode 100644 index 0000000..9d2599e --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/TcpConnector.php @@ -0,0 +1,173 @@ +loop = $loop ?: Loop::get(); + $this->context = $context; + } + + public function connect($uri) + { + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + } + + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $uri . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + $ip = \trim($parts['host'], '[]'); + if (@\inet_pton($ip) === false) { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + // use context given in constructor + $context = array( + 'socket' => $this->context + ); + + // parse arguments from query component of URI + $args = array(); + if (isset($parts['query'])) { + \parse_str($parts['query'], $args); + } + + // If an original hostname has been given, use this for TLS setup. + // This can happen due to layers of nested connectors, such as a + // DnsConnector reporting its original hostname. + // These context options are here in case TLS is enabled later on this stream. + // If TLS is not enabled later, this doesn't hurt either. + if (isset($args['hostname'])) { + $context['ssl'] = array( + 'SNI_enabled' => true, + 'peer_name' => $args['hostname'] + ); + + // Legacy PHP < 5.6 ignores peer_name and requires legacy context options instead. + // The SNI_server_name context option has to be set here during construction, + // as legacy PHP ignores any values set later. + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID < 50600) { + $context['ssl'] += array( + 'SNI_server_name' => $args['hostname'], + 'CN_match' => $args['hostname'] + ); + } + // @codeCoverageIgnoreEnd + } + + // latest versions of PHP no longer accept any other URI components and + // HHVM fails to parse URIs with a query but no path, so let's simplify our URI here + $remote = 'tcp://' . $parts['host'] . ':' . $parts['port']; + + $stream = @\stream_socket_client( + $remote, + $errno, + $errstr, + 0, + \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT, + \stream_context_create($context) + ); + + if (false === $stream) { + return Promise\reject(new \RuntimeException( + 'Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno), + $errno + )); + } + + // wait for connection + $loop = $this->loop; + return new Promise\Promise(function ($resolve, $reject) use ($loop, $stream, $uri) { + $loop->addWriteStream($stream, function ($stream) use ($loop, $resolve, $reject, $uri) { + $loop->removeWriteStream($stream); + + // The following hack looks like the only way to + // detect connection refused errors with PHP's stream sockets. + if (false === \stream_socket_get_name($stream, true)) { + // If we reach this point, we know the connection is dead, but we don't know the underlying error condition. + // @codeCoverageIgnoreStart + if (\function_exists('socket_import_stream')) { + // actual socket errno and errstr can be retrieved with ext-sockets on PHP 5.4+ + $socket = \socket_import_stream($stream); + $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR); + $errstr = \socket_strerror($errno); + } elseif (\PHP_OS === 'Linux') { + // Linux reports socket errno and errstr again when trying to write to the dead socket. + // Suppress error reporting to get error message below and close dead socket before rejecting. + // This is only known to work on Linux, Mac and Windows are known to not support this. + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fwrite(): send of 1 bytes failed with errno=111 Connection refused + \preg_match('/errno=(\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + + \fwrite($stream, \PHP_EOL); + + \restore_error_handler(); + } else { + // Not on Linux and ext-sockets not available? Too bad. + $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111; + $errstr = 'Connection refused?'; + } + // @codeCoverageIgnoreEnd + + \fclose($stream); + $reject(new \RuntimeException( + 'Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno), + $errno + )); + } else { + $resolve(new Connection($stream, $loop)); + } + }); + }, function () use ($loop, $stream, $uri) { + $loop->removeWriteStream($stream); + \fclose($stream); + + // @codeCoverageIgnoreStart + // legacy PHP 5.3 sometimes requires a second close call (see tests) + if (\PHP_VERSION_ID < 50400 && \is_resource($stream)) { + \fclose($stream); + } + // @codeCoverageIgnoreEnd + + throw new \RuntimeException( + 'Connection to ' . $uri . ' cancelled during TCP/IP handshake (ECONNABORTED)', + \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103 + ); + }); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/TcpServer.php b/trilhas_poo/vendor/react/socket/src/TcpServer.php new file mode 100644 index 0000000..01b2b46 --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/TcpServer.php @@ -0,0 +1,262 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class TcpServer extends EventEmitter implements ServerInterface +{ + private $master; + private $loop; + private $listening = false; + + /** + * Creates a plaintext TCP/IP socket server and starts listening on the given address + * + * This starts accepting new incoming connections on the given address. + * See also the `connection event` documented in the `ServerInterface` + * for more details. + * + * ```php + * $server = new React\Socket\TcpServer(8080); + * ``` + * + * As above, the `$uri` parameter can consist of only a port, in which case the + * server will default to listening on the localhost address `127.0.0.1`, + * which means it will not be reachable from outside of this system. + * + * In order to use a random port assignment, you can use the port `0`: + * + * ```php + * $server = new React\Socket\TcpServer(0); + * $address = $server->getAddress(); + * ``` + * + * In order to change the host the socket is listening on, you can provide an IP + * address through the first parameter provided to the constructor, optionally + * preceded by the `tcp://` scheme: + * + * ```php + * $server = new React\Socket\TcpServer('192.168.0.1:8080'); + * ``` + * + * If you want to listen on an IPv6 address, you MUST enclose the host in square + * brackets: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080'); + * ``` + * + * If the given URI is invalid, does not contain a port, any other scheme or if it + * contains a hostname, it will throw an `InvalidArgumentException`: + * + * ```php + * // throws InvalidArgumentException due to missing port + * $server = new React\Socket\TcpServer('127.0.0.1'); + * ``` + * + * If the given URI appears to be valid, but listening on it fails (such as if port + * is already in use or port below 1024 may require root access etc.), it will + * throw a `RuntimeException`: + * + * ```php + * $first = new React\Socket\TcpServer(8080); + * + * // throws RuntimeException because port is already in use + * $second = new React\Socket\TcpServer(8080); + * ``` + * + * Note that these error conditions may vary depending on your system and/or + * configuration. + * See the exception message and code for more details about the actual error + * condition. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) + * for the underlying stream socket resource like this: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080', null, array( + * 'backlog' => 200, + * 'so_reuseport' => true, + * 'ipv6_v6only' => true + * )); + * ``` + * + * Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * The `backlog` context option defaults to `511` unless given explicitly. + * + * @param string|int $uri + * @param ?LoopInterface $loop + * @param array $context + * @throws InvalidArgumentException if the listening address is invalid + * @throws RuntimeException if listening on this address fails (already in use etc.) + */ + public function __construct($uri, $loop = null, array $context = array()) + { + if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1 + throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface'); + } + + $this->loop = $loop ?: Loop::get(); + + // a single port has been given => assume localhost + if ((string)(int)$uri === (string)$uri) { + $uri = '127.0.0.1:' . $uri; + } + + // assume default scheme if none has been given + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + } + + // parse_url() does not accept null ports (random port assignment) => manually remove + if (\substr($uri, -2) === ':0') { + $parts = \parse_url(\substr($uri, 0, -2)); + if ($parts) { + $parts['port'] = 0; + } + } else { + $parts = \parse_url($uri); + } + + // ensure URI contains TCP scheme, host and port + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + throw new \InvalidArgumentException( + 'Invalid URI "' . $uri . '" given (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + ); + } + + if (@\inet_pton(\trim($parts['host'], '[]')) === false) { + throw new \InvalidArgumentException( + 'Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + ); + } + + $this->master = @\stream_socket_server( + $uri, + $errno, + $errstr, + \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, + \stream_context_create(array('socket' => $context + array('backlog' => 511))) + ); + if (false === $this->master) { + if ($errno === 0) { + // PHP does not seem to report errno, so match errno from errstr + // @link https://3v4l.org/3qOBl + $errno = SocketServer::errno($errstr); + } + + throw new \RuntimeException( + 'Failed to listen on "' . $uri . '": ' . $errstr . SocketServer::errconst($errno), + $errno + ); + } + \stream_set_blocking($this->master, false); + + $this->resume(); + } + + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + + $address = \stream_socket_get_name($this->master, false); + + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore + } + + return 'tcp://' . $address; + } + + public function pause() + { + if (!$this->listening) { + return; + } + + $this->loop->removeReadStream($this->master); + $this->listening = false; + } + + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use ($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = true; + } + + public function close() + { + if (!\is_resource($this->master)) { + return; + } + + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleConnection($socket) + { + $this->emit('connection', array( + new Connection($socket, $this->loop) + )); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/TimeoutConnector.php b/trilhas_poo/vendor/react/socket/src/TimeoutConnector.php new file mode 100644 index 0000000..9ef252f --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/TimeoutConnector.php @@ -0,0 +1,79 @@ +connector = $connector; + $this->timeout = $timeout; + $this->loop = $loop ?: Loop::get(); + } + + public function connect($uri) + { + $promise = $this->connector->connect($uri); + + $loop = $this->loop; + $time = $this->timeout; + return new Promise(function ($resolve, $reject) use ($loop, $time, $promise, $uri) { + $timer = null; + $promise = $promise->then(function ($v) use (&$timer, $loop, $resolve) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $resolve($v); + }, function ($v) use (&$timer, $loop, $reject) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $reject($v); + }); + + // promise already resolved => no need to start timer + if ($timer === false) { + return; + } + + // start timeout timer which will cancel the pending promise + $timer = $loop->addTimer($time, function () use ($time, &$promise, $reject, $uri) { + $reject(new \RuntimeException( + 'Connection to ' . $uri . ' timed out after ' . $time . ' seconds (ETIMEDOUT)', + \defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 110 + )); + + // Cancel pending connection to clean up any underlying resources and references. + // Avoid garbage references in call stack by passing pending promise by reference. + assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + }, function () use (&$promise) { + // Cancelling this promise will cancel the pending connection, thus triggering the rejection logic above. + // Avoid garbage references in call stack by passing pending promise by reference. + assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/UnixConnector.php b/trilhas_poo/vendor/react/socket/src/UnixConnector.php new file mode 100644 index 0000000..95f932c --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/UnixConnector.php @@ -0,0 +1,58 @@ +loop = $loop ?: Loop::get(); + } + + public function connect($path) + { + if (\strpos($path, '://') === false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + return Promise\reject(new \InvalidArgumentException( + 'Given URI "' . $path . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + )); + } + + $resource = @\stream_socket_client($path, $errno, $errstr, 1.0); + + if (!$resource) { + return Promise\reject(new \RuntimeException( + 'Unable to connect to unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno), + $errno + )); + } + + $connection = new Connection($resource, $this->loop); + $connection->unix = true; + + return Promise\resolve($connection); + } +} diff --git a/trilhas_poo/vendor/react/socket/src/UnixServer.php b/trilhas_poo/vendor/react/socket/src/UnixServer.php new file mode 100644 index 0000000..27b014d --- /dev/null +++ b/trilhas_poo/vendor/react/socket/src/UnixServer.php @@ -0,0 +1,162 @@ +loop = $loop ?: Loop::get(); + + if (\strpos($path, '://') === false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + throw new \InvalidArgumentException( + 'Given URI "' . $path . '" is invalid (EINVAL)', + \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22) + ); + } + + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use (&$errno, &$errstr) { + // PHP does not seem to report errno/errstr for Unix domain sockets (UDS) right now. + // This only applies to UDS server sockets, see also https://3v4l.org/NAhpr. + // Parse PHP warning message containing unknown error, HHVM reports proper info at least. + if (\preg_match('/\(([^\)]+)\)|\[(\d+)\]: (.*)/', $error, $match)) { + $errstr = isset($match[3]) ? $match['3'] : $match[1]; + $errno = isset($match[2]) ? (int)$match[2] : 0; + } + }); + + $this->master = \stream_socket_server( + $path, + $errno, + $errstr, + \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, + \stream_context_create(array('socket' => $context)) + ); + + \restore_error_handler(); + + if (false === $this->master) { + throw new \RuntimeException( + 'Failed to listen on Unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno), + $errno + ); + } + \stream_set_blocking($this->master, 0); + + $this->resume(); + } + + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + + return 'unix://' . \stream_socket_get_name($this->master, false); + } + + public function pause() + { + if (!$this->listening) { + return; + } + + $this->loop->removeReadStream($this->master); + $this->listening = false; + } + + public function resume() + { + if ($this->listening || !is_resource($this->master)) { + return; + } + + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use ($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = true; + } + + public function close() + { + if (!\is_resource($this->master)) { + return; + } + + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleConnection($socket) + { + $connection = new Connection($socket, $this->loop); + $connection->unix = true; + + $this->emit('connection', array( + $connection + )); + } +} diff --git a/trilhas_poo/vendor/react/stream/CHANGELOG.md b/trilhas_poo/vendor/react/stream/CHANGELOG.md new file mode 100644 index 0000000..639db65 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/CHANGELOG.md @@ -0,0 +1,460 @@ +# Changelog + +## 1.4.0 (2024-06-11) + +* Feature: Improve PHP 8.4+ support by avoiding implicitly nullable type declarations. + (#179 by @clue) + +* Feature: Full PHP 8.3 compatibility. + (#172 by @clue) + +* Fix: Fix `drain` event of `ThroughStream` to handle potential race condition. + (#171 by @clue) + +## 1.3.0 (2023-06-16) + +* Feature: Full PHP 8.1 and PHP 8.2 compatibility. + (#160 by @SimonFrings, #165 by @clue and #169 by @WyriHaximus) + +* Feature: Avoid unneeded syscall when creating non-blocking `DuplexResourceStream`. + (#164 by @clue) + +* Minor documentation improvements. + (#161 by @mrsimonbennett, #162 by @SimonFrings and #166 by @nhedger) + +* Improve test suite and project setup and report failed assertions. + (#168 and #170 by @clue and #163 by @SimonFrings) + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#159 by @clue) + + ```php + // old (still supported) + $stream = new ReadableResourceStream($resource, $loop); + $stream = new WritabeResourceStream($resource, $loop); + $stream = new DuplexResourceStream($resource, $loop); + + // new (using default loop) + $stream = new ReadableResourceStream($resource); + $stream = new WritabeResourceStream($resource); + $stream = new DuplexResourceStream($resource); + ``` + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config, run tests on PHP 8 and add full core team to the license. + (#153, #156 and #157 by @SimonFrings and #154 by @WyriHaximus) + +## 1.1.1 (2020-05-04) + +* Fix: Fix faulty write buffer behavior when sending large data chunks over TLS (Mac OS X only). + (#150 by @clue) + +* Minor code style improvements to fix phpstan analysis warnings and + add `.gitattributes` to exclude dev files from exports. + (#140 by @flow-control and #144 by @reedy) + +* Improve test suite to run tests on PHP 7.4 and simplify test matrix. + (#147 by @clue) + +## 1.1.0 (2019-01-01) + +* Improvement: Increase performance by optimizing global function and constant look ups. + (#137 by @WyriHaximus) + +* Travis: Test against PHP 7.3. + (#138 by @WyriHaximus) + +* Fix: Ignore empty reads. + (#139 by @WyriHaximus) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.7.7 release. + +## 0.7.7 (2018-01-19) + +* Improve test suite by fixing forward compatibility with upcoming EventLoop + releases, avoid risky tests and add test group to skip integration tests + relying on internet connection and apply appropriate test timeouts. + (#128, #131 and #132 by @clue) + +## 0.7.6 (2017-12-21) + +* Fix: Work around reading from unbuffered pipe stream in legacy PHP < 5.4.28 and PHP < 5.5.12 + (#126 by @clue) + +* Improve test suite by simplifying test bootstrapping logic via Composer and + test against PHP 7.2 + (#127 by @clue and #124 by @carusogabriel) + +## 0.7.5 (2017-11-20) + +* Fix: Igore excessive `fopen()` mode flags for `WritableResourceStream` + (#119 by @clue) + +* Fix: Fix forward compatibility with upcoming EventLoop releases + (#121 by @clue) + +* Restructure examples to ease getting started + (#123 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#122 by @gabriel-caruso and #120 by @clue) + +## 0.7.4 (2017-10-11) + +* Fix: Remove event listeners from `CompositeStream` once closed and + remove undocumented left-over `close` event argument + (#116 by @clue) + +* Minor documentation improvements: Fix wrong class name in example, + fix typos in README and + fix forward compatibility with upcoming EventLoop releases in example + (#113 by @docteurklein and #114 and #115 by @clue) + +* Improve test suite by running against Mac OS X on Travis + (#112 by @clue) + +## 0.7.3 (2017-08-05) + +* Improvement: Support Événement 3.0 a long side 2.0 and 1.0 + (#108 by @WyriHaximus) + +* Readme: Corrected loop initialization in usage example + (#109 by @pulyavin) + +* Travis: Lock linux distribution preventing future builds from breaking + (#110 by @clue) + +## 0.7.2 (2017-06-15) + +* Bug fix: WritableResourceStream: Close the underlying stream when closing the stream. + (#107 by @WyriHaximus) + +## 0.7.1 (2017-05-20) + +* Feature: Add optional `$writeChunkSize` parameter to limit maximum number of + bytes to write at once. + (#105 by @clue) + + ```php + $stream = new WritableResourceStream(STDOUT, $loop, null, 8192); + ``` + +* Ignore HHVM test failures for now until Travis tests work again + (#106 by @clue) + +## 0.7.0 (2017-05-04) + +* Removed / BC break: Remove deprecated and unneeded functionality + (#45, #87, #90, #91 and #93 by @clue) + + * Remove deprecated `Stream` class, use `DuplexResourceStream` instead + (#87 by @clue) + + * Remove public `$buffer` property, use new constructor parameters instead + (#91 by @clue) + + * Remove public `$stream` property from all resource streams + (#90 by @clue) + + * Remove undocumented and now unused `ReadableStream` and `WritableStream` + (#93 by @clue) + + * Remove `BufferedSink` + (#45 by @clue) + +* Feature / BC break: Simplify `ThroughStream` by using data callback instead of + inheritance. It is now a direct implementation of `DuplexStreamInterface`. + (#88 and #89 by @clue) + + ```php + $through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; + }); + $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + + $through->write(array(2, true)); + ``` + +* Feature / BC break: The `CompositeStream` starts closed if either side is + already closed and forwards pause to pipe source on first write attempt. + (#96 and #103 by @clue) + + If either side of the composite stream closes, it will also close the other + side. We now also ensure that if either side is already closed during + instantiation, it will also close the other side. + +* BC break: Mark all classes as `final` and + mark internal API as `private` to discourage inheritance + (#95 and #99 by @clue) + +* Feature / BC break: Only emit `error` event for fatal errors + (#92 by @clue) + + > The `error` event was previously also allowed to be emitted for non-fatal + errors, but our implementations actually only ever emitted this as a fatal + error and then closed the stream. + +* Feature: Explicitly allow custom events and exclude any semantics + (#97 by @clue) + +* Strict definition for event callback functions + (#101 by @clue) + +* Support legacy PHP 5.3 through PHP 7.1 and HHVM and improve usage documentation + (#100 and #102 by @clue) + +* Actually require all dependencies so this is self-contained and improve + forward compatibility with EventLoop v1.0 and v0.5 + (#94 and #98 by @clue) + +## 0.6.0 (2017-03-26) + +* Feature / Fix / BC break: Add `DuplexResourceStream` and deprecate `Stream` + (#85 by @clue) + + ```php + // old (does still work for BC reasons) + $stream = new Stream($connection, $loop); + + // new + $stream = new DuplexResourceStream($connection, $loop); + ``` + + Note that the `DuplexResourceStream` now rejects read-only or write-only + streams, so this may affect BC. If you want a read-only or write-only + resource, use `ReadableResourceStream` or `WritableResourceStream` instead of + `DuplexResourceStream`. + + > BC note: This class was previously called `Stream`. The `Stream` class still + exists for BC reasons and will be removed in future versions of this package. + +* Feature / BC break: Add `WritableResourceStream` (previously called `Buffer`) + (#84 by @clue) + + ```php + // old + $stream = new Buffer(STDOUT, $loop); + + // new + $stream = new WritableResourceStream(STDOUT, $loop); + ``` + +* Feature: Add `ReadableResourceStream` + (#83 by @clue) + + ```php + $stream = new ReadableResourceStream(STDIN, $loop); + ``` + +* Fix / BC Break: Enforce using non-blocking I/O + (#46 by @clue) + + > BC note: This is known to affect process pipes on Windows which do not + support non-blocking I/O and could thus block the whole EventLoop previously. + +* Feature / Fix / BC break: Consistent semantics for + `DuplexStreamInterface::end()` to ensure it SHOULD also end readable side + (#86 by @clue) + +* Fix: Do not use unbuffered reads on pipe streams for legacy PHP < 5.4 + (#80 by @clue) + +## 0.5.0 (2017-03-08) + +* Feature / BC break: Consistent `end` event semantics (EOF) + (#70 by @clue) + + The `end` event will now only be emitted for a *successful* end, not if the + stream closes due to an unrecoverable `error` event or if you call `close()` + explicitly. + If you want to detect when the stream closes (terminates), use the `close` + event instead. + +* BC break: Remove custom (undocumented) `full-drain` event from `Buffer` + (#63 and #68 by @clue) + + > The `full-drain` event was undocumented and mostly used internally. + Relying on this event has attracted some low-quality code in the past, so + we've removed this from the public API in order to work out a better + solution instead. + If you want to detect when the buffer finishes flushing data to the stream, + you may want to look into its `end()` method or the `close` event instead. + +* Feature / BC break: Consistent event semantics and documentation, + explicitly state *when* events will be emitted and *which* arguments they + receive. + (#73 and #69 by @clue) + + The documentation now explicitly defines each event and its arguments. + Custom events and event arguments are still supported. + Most notably, all defined events only receive inherently required event + arguments and no longer transmit the instance they are emitted on for + consistency and performance reasons. + + ```php + // old (inconsistent and not supported by all implementations) + $stream->on('data', function ($data, $stream) { + // process $data + }); + + // new (consistent throughout the whole ecosystem) + $stream->on('data', function ($data) use ($stream) { + // process $data + }); + ``` + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature / BC break: Consistent method semantics and documentation + (#72 by @clue) + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature: Consistent `pipe()` semantics for closed and closing streams + (#71 from @clue) + + The source stream will now always be paused via `pause()` when the + destination stream closes. Also, properly stop piping if the source + stream closes and remove all event forwarding. + +* Improve test suite by adding PHPUnit to `require-dev` and improving coverage. + (#74 and #75 by @clue, #66 by @nawarian) + +## 0.4.6 (2017-01-25) + +* Feature: The `Buffer` can now be injected into the `Stream` (or be used standalone) + (#62 by @clue) + +* Fix: Forward `close` event only once for `CompositeStream` and `ThroughStream` + (#60 by @clue) + +* Fix: Consistent `close` event behavior for `Buffer` + (#61 by @clue) + +## 0.4.5 (2016-11-13) + +* Feature: Support setting read buffer size to `null` (infinite) + (#42 by @clue) + +* Fix: Do not emit `full-drain` event if `Buffer` is closed during `drain` event + (#55 by @clue) + +* Vastly improved performance by factor of 10x to 20x. + Raise default buffer sizes to 64 KiB and simplify and improve error handling + and unneeded function calls. + (#53, #55, #56 by @clue) + +## 0.4.4 (2016-08-22) + +* Bug fix: Emit `error` event and close `Stream` when accessing the underlying + stream resource fails with a permanent error. + (#52 and #40 by @clue, #25 by @lysenkobv) + +* Bug fix: Do not emit empty `data` event if nothing has been read (stream reached EOF) + (#39 by @clue) + +* Bug fix: Ignore empty writes to `Buffer` + (#51 by @clue) + +* Add benchmarking script to measure throughput in CI + (#41 by @clue) + +## 0.4.3 (2015-10-07) + +* Bug fix: Read buffer to 0 fixes error with libevent and large quantity of I/O (@mbonneau) +* Bug fix: No double-write during drain call (@arnaud-lb) +* Bug fix: Support HHVM (@clue) +* Adjust compatibility to 5.3 (@clue) + +## 0.4.2 (2014-09-09) + +* Added DuplexStreamInterface +* Stream sets stream resources to non-blocking +* Fixed potential race condition in pipe + +## 0.4.1 (2014-04-13) + +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: [Stream] Fixed 100% CPU spike from non-empty write buffer on closed stream + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.3 (2013-07-08) + +* Bug fix: [Stream] Correctly detect closed connections + +## 0.3.2 (2013-05-10) + +* Bug fix: [Stream] Make sure CompositeStream is closed properly + +## 0.3.1 (2013-04-21) + +* Bug fix: [Stream] Allow any `ReadableStreamInterface` on `BufferedSink::createPromise()` + +## 0.3.0 (2013-04-14) + +* Feature: [Stream] Factory method for BufferedSink + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.5 (2012-11-26) + +* Feature: Make BufferedSink trigger progress events on the promise (@jsor) + +## 0.2.4 (2012-11-18) + +* Feature: Added ThroughStream, CompositeStream, ReadableStream and WritableStream +* Feature: Added BufferedSink + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Version bump + +## 0.2.1 (2012-10-14) + +* Bug fix: Check for EOF in `Buffer::write()` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Bug fix: Testing and functional against PHP >= 5.3.3 and <= 5.3.8 + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/trilhas_poo/vendor/react/stream/LICENSE b/trilhas_poo/vendor/react/stream/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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/trilhas_poo/vendor/react/stream/README.md b/trilhas_poo/vendor/react/stream/README.md new file mode 100644 index 0000000..9c0468a --- /dev/null +++ b/trilhas_poo/vendor/react/stream/README.md @@ -0,0 +1,1249 @@ +# Stream + +[![CI status](https://github.com/reactphp/stream/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/stream/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/stream?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/stream) + +Event-driven readable and writable streams for non-blocking I/O in [ReactPHP](https://reactphp.org/). + +In order to make the [EventLoop](https://github.com/reactphp/event-loop) +easier to use, this component introduces the powerful concept of "streams". +Streams allow you to efficiently process huge amounts of data (such as a multi +Gigabyte file download) in small chunks without having to store everything in +memory at once. +They are very similar to the streams found in PHP itself, +but have an interface more suited for async, non-blocking I/O. + +**Table of contents** + +* [Stream usage](#stream-usage) + * [ReadableStreamInterface](#readablestreaminterface) + * [data event](#data-event) + * [end event](#end-event) + * [error event](#error-event) + * [close event](#close-event) + * [isReadable()](#isreadable) + * [pause()](#pause) + * [resume()](#resume) + * [pipe()](#pipe) + * [close()](#close) + * [WritableStreamInterface](#writablestreaminterface) + * [drain event](#drain-event) + * [pipe event](#pipe-event) + * [error event](#error-event-1) + * [close event](#close-event-1) + * [isWritable()](#iswritable) + * [write()](#write) + * [end()](#end) + * [close()](#close-1) + * [DuplexStreamInterface](#duplexstreaminterface) +* [Creating streams](#creating-streams) + * [ReadableResourceStream](#readableresourcestream) + * [WritableResourceStream](#writableresourcestream) + * [DuplexResourceStream](#duplexresourcestream) + * [ThroughStream](#throughstream) + * [CompositeStream](#compositestream) +* [Usage](#usage) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Stream usage + +ReactPHP uses the concept of "streams" throughout its ecosystem to provide a +consistent higher-level abstraction for processing streams of arbitrary data +contents and size. +While a stream itself is a quite low-level concept, it can be used as a powerful +abstraction to build higher-level components and protocols on top. + +If you're new to this concept, it helps to think of them as a water pipe: +You can consume water from a source or you can produce water and forward (pipe) +it to any destination (sink). + +Similarly, streams can either be + +* readable (such as `STDIN` terminal input) or +* writable (such as `STDOUT` terminal output) or +* duplex (both readable *and* writable, such as a TCP/IP connection) + +Accordingly, this package defines the following three interfaces + +* [`ReadableStreamInterface`](#readablestreaminterface) +* [`WritableStreamInterface`](#writablestreaminterface) +* [`DuplexStreamInterface`](#duplexstreaminterface) + +### ReadableStreamInterface + +The `ReadableStreamInterface` is responsible for providing an interface for +read-only streams and the readable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### data event + +The `data` event will be emitted whenever some data was read/received +from this source stream. +The event receives a single mixed argument for incoming data. + +```php +$stream->on('data', function ($data) { + echo $data; +}); +``` + +This event MAY be emitted any number of times, which may be zero times if +this stream does not send any data at all. +It SHOULD not be emitted after an `end` or `close` event. + +The given `$data` argument may be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit the raw (binary) payload data that is received over the wire as +chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end event + +The `end` event will be emitted once the source stream has successfully +reached the end of the stream (EOF). + +```php +$stream->on('end', function () { + echo 'END'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +a successful end was detected. +It SHOULD NOT be emitted after a previous `end` or `close` event. +It MUST NOT be emitted if the stream closes due to a non-successful +end, such as after a previous `error` event. + +After the stream is ended, it MUST switch to non-readable mode, +see also `isReadable()`. + +This event will only be emitted if the *end* was reached successfully, +not if the stream was interrupted by an unrecoverable error or explicitly +closed. Not all streams know this concept of a "successful end". +Many use-cases involve detecting when the stream closes (terminates) +instead, in this case you should use the `close` event. +After the stream emits an `end` event, it SHOULD usually be followed by a +`close` event. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit this event if either the remote side closes the connection or +a file handle was successfully read until reaching its end (EOF). + +Note that this event should not be confused with the `end()` method. +This event defines a successful end *reading* from a source stream, while +the `end()` method defines *writing* a successful end to a destination +stream. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to read from this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$server->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error or after an unexpected `data` or premature +`end` event. +It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-readable mode, see +also `close()` and `isReadable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and do not make assumption about data +boundaries (such as unexpected `data` or premature `end` events). +In other words, many lower-level protocols (such as TCP/IP) may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-readable mode, +see also `isReadable()`. + +Unlike the `end` event, this event SHOULD be emitted whenever the stream +closes, irrespective of whether this happens implicitly due to an +unrecoverable error or explicitly when either side closes the stream. +If you only want to detect a *successful* end, you should use the `end` +event instead. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after reading a *successful* `end` +event or after a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this event should not be confused with the `end` event. + +#### isReadable() + +The `isReadable(): bool` method can be used to +check whether this stream is in a readable state (not closed already). + +This method can be used to check if the stream still accepts incoming +data events or if it is ended or closed already. +Once the stream is non-readable, no further `data` or `end` events SHOULD +be emitted. + +```php +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +A successfully opened stream always MUST start in readable mode. + +Once the stream ends or closes, it MUST switch to non-readable mode. +This can happen any time, explicitly through `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-readable mode, it MUST NOT transition +back to readable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `isWritable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### pause() + +The `pause(): void` method can be used to +pause reading incoming data events. + +Removes the data source file descriptor from the event loop. This +allows you to throttle incoming data. + +Unless otherwise noted, a successfully opened stream SHOULD NOT start +in paused state. + +Once the stream is paused, no futher `data` or `end` events SHOULD +be emitted. + +```php +$stream->pause(); + +$stream->on('data', assertShouldNeverCalled()); +$stream->on('end', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +stream MAY continue emitting `data` events. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. + +See also `resume()`. + +#### resume() + +The `resume(): void` method can be used to +resume reading incoming data events. + +Re-attach the data source after a previous `pause()`. + +```php +$stream->pause(); + +Loop::addTimer(1.0, function () use ($stream) { + $stream->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + +See also `pause()`. + +#### pipe() + +The `pipe(WritableStreamInterface $dest, array $options = [])` method can be used to +pipe all the data from this readable source into the given writable destination. + +Automatically sends all incoming data to the destination. +Automatically throttles the source based on what the destination can handle. + +```php +$source->pipe($dest); +``` + +Similarly, you can also pipe an instance implementing `DuplexStreamInterface` +into itself in order to write back all the data that is received. +This may be a useful feature for a TCP/IP echo service: + +```php +$connection->pipe($connection); +``` + +This method returns the destination stream as-is, which can be used to +set up chains of piped streams: + +```php +$source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); +``` + +By default, this will call `end()` on the destination stream once the +source stream emits an `end` event. This can be disabled like this: + +```php +$source->pipe($dest, array('end' => false)); +``` + +Note that this only applies to the `end` event. +If an `error` or explicit `close` event happens on the source stream, +you'll have to manually close the destination stream: + +```php +$source->pipe($dest); +$source->on('close', function () use ($dest) { + $dest->end('BYE!'); +}); +``` + +If the source stream is not readable (closed state), then this is a NO-OP. + +```php +$source->close(); +$source->pipe($dest); // NO-OP +``` + +If the destinantion stream is not writable (closed state), then this will simply +throttle (pause) the source stream: + +```php +$dest->close(); +$source->pipe($dest); // calls $source->pause() +``` + +Similarly, if the destination stream is closed while the pipe is still +active, it will also throttle (pause) the source stream: + +```php +$source->pipe($dest); +$dest->close(); // calls $source->pause() +``` + +Once the pipe is set up successfully, the destination stream MUST emit +a `pipe` event with this source stream an event argument. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to (forcefully) close the stream. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-readable +mode, see also `isReadable()`. +This means that no further `data` or `end` events SHOULD be emitted. + +```php +$stream->close(); +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this method should not be confused with the `end()` method. + +### WritableStreamInterface + +The `WritableStreamInterface` is responsible for providing an interface for +write-only streams and the writable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### drain event + +The `drain` event will be emitted whenever the write buffer became full +previously and is now ready to accept more data. + +```php +$stream->on('drain', function () use ($stream) { + echo 'Stream is now ready to accept more data'; +}); +``` + +This event SHOULD be emitted once every time the buffer became full +previously and is now ready to accept more data. +In other words, this event MAY be emitted any number of times, which may +be zero times if the buffer never became full in the first place. +This event SHOULD NOT be emitted if the buffer has not become full +previously. + +This event is mostly used internally, see also `write()` for more details. + +#### pipe event + +The `pipe` event will be emitted whenever a readable stream is `pipe()`d +into this stream. +The event receives a single `ReadableStreamInterface` argument for the +source stream. + +```php +$stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + echo 'Now receiving piped data'; + + // explicitly close target if source emits an error + $source->on('error', function () use ($stream) { + $stream->close(); + }); +}); + +$source->pipe($stream); +``` + +This event MUST be emitted once for each readable stream that is +successfully piped into this destination stream. +In other words, this event MAY be emitted any number of times, which may +be zero times if no stream is ever piped into this stream. +This event MUST NOT be emitted if either the source is not readable +(closed already) or this destination is not writable (closed already). + +This event is mostly used internally, see also `pipe()` for more details. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to write to this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$stream->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error. +It SHOULD NOT be emitted after a previous `error` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-writable mode, see +also `close()` and `isWritable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-writable mode, +see also `isWritable()`. + +This event SHOULD be emitted whenever the stream closes, irrespective of +whether this happens implicitly due to an unrecoverable error or +explicitly when either side closes the stream. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after flushing the buffer from +the `end()` method, after receiving a *successful* `end` event or after +a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. +Note that this event should not be confused with the `end` event. + +#### isWritable() + +The `isWritable(): bool` method can be used to +check whether this stream is in a writable state (not closed already). + +This method can be used to check if the stream still accepts writing +any data or if it is ended or closed already. +Writing any data to a non-writable stream is a NO-OP: + +```php +assert($stream->isWritable() === false); + +$stream->write('end'); // NO-OP +$stream->end('end'); // NO-OP +``` + +A successfully opened stream always MUST start in writable mode. + +Once the stream ends or closes, it MUST switch to non-writable mode. +This can happen any time, explicitly through `end()` or `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-writable mode, it MUST NOT transition +back to writable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `isReadable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### write() + +The `write(mixed $data): bool` method can be used to +write some data into the stream. + +A successful write MUST be confirmed with a boolean `true`, which means +that either the data was written (flushed) immediately or is buffered and +scheduled for a future write. Note that this interface gives you no +control over explicitly flushing the buffered data, as finding the +appropriate time for this is beyond the scope of this interface and left +up to the implementation of this interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +If a stream cannot handle writing (or flushing) the data, it SHOULD emit +an `error` event and MAY `close()` the stream if it can not recover from +this error. + +If the internal buffer is full after adding `$data`, then `write()` +SHOULD return `false`, indicating that the caller should stop sending +data until the buffer drains. +The stream SHOULD send a `drain` event once the buffer is ready to accept +more data. + +Similarly, if the stream is not writable (already in a closed state) +it MUST NOT process the given `$data` and SHOULD return `false`, +indicating that the caller should stop sending data. + +The given `$data` argument MAY be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will only accept the raw (binary) payload data that is transferred over +the wire as chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end() + +The `end(mixed $data = null): void` method can be used to +successfully end the stream (after optionally sending some final data). + +This method can be used to successfully end the stream, i.e. close +the stream after sending out all data that is currently buffered. + +```php +$stream->write('hello'); +$stream->write('world'); +$stream->end(); +``` + +If there's no data currently buffered and nothing to be flushed, then +this method MAY `close()` the stream immediately. + +If there's still data in the buffer that needs to be flushed first, then +this method SHOULD try to write out this data and only then `close()` +the stream. +Once the stream is closed, it SHOULD emit a `close` event. + +Note that this interface gives you no control over explicitly flushing +the buffered data, as finding the appropriate time for this is beyond the +scope of this interface and left up to the implementation of this +interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +You can optionally pass some final data that is written to the stream +before ending the stream. If a non-`null` value is given as `$data`, then +this method will behave just like calling `write($data)` before ending +with no data. + +```php +// shorter version +$stream->end('bye'); + +// same as longer version +$stream->write('bye'); +$stream->end(); +``` + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->end(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +If this stream is a `DuplexStreamInterface`, calling this method SHOULD +also end its readable side, unless the stream supports half-open mode. +In other words, after calling this method, these streams SHOULD switch +into non-writable AND non-readable mode, see also `isReadable()`. +This implies that in this case, the stream SHOULD NOT emit any `data` +or `end` events anymore. +Streams MAY choose to use the `pause()` method logic for this, but +special care may have to be taken to ensure a following call to the +`resume()` method SHOULD NOT continue emitting readable events. + +Note that this method should not be confused with the `close()` method. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to forcefully close the stream, i.e. close +the stream without waiting for any buffered data to be flushed. +If there's still data in the buffer, this data SHOULD be discarded. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->close(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +Note that this method should not be confused with the `end()` method. +Unlike the `end()` method, this method does not take care of any existing +buffers and simply discards any buffer contents. +Likewise, this method may also be called after calling `end()` on a +stream in order to stop waiting for the stream to flush its final data. + +```php +$stream->end(); +Loop::addTimer(1.0, function () use ($stream) { + $stream->close(); +}); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. + +### DuplexStreamInterface + +The `DuplexStreamInterface` is responsible for providing an interface for +duplex streams (both readable and writable). + +It builds on top of the existing interfaces for readable and writable streams +and follows the exact same method and event semantics. +If you're new to this concept, you should look into the +`ReadableStreamInterface` and `WritableStreamInterface` first. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to the same events defined +on the `ReadbleStreamInterface` and `WritableStreamInterface`. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +See also [`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) for more details. + +## Creating streams + +ReactPHP uses the concept of "streams" throughout its ecosystem, so that +many higher-level consumers of this package only deal with +[stream usage](#stream-usage). +This implies that stream instances are most often created within some +higher-level components and many consumers never actually have to deal with +creating a stream instance. + +* Use [react/socket](https://github.com/reactphp/socket) + if you want to accept incoming or establish outgoing plaintext TCP/IP or + secure TLS socket connection streams. +* Use [react/http](https://github.com/reactphp/http) + if you want to receive an incoming HTTP request body streams. +* Use [react/child-process](https://github.com/reactphp/child-process) + if you want to communicate with child processes via process pipes such as + STDIN, STDOUT, STDERR etc. +* Use experimental [react/filesystem](https://github.com/reactphp/filesystem) + if you want to read from / write to the filesystem. +* See also the last chapter for [more real-world applications](#more). + +However, if you are writing a lower-level component or want to create a stream +instance from a stream resource, then the following chapter is for you. + +> Note that the following examples use `fopen()` and `stream_socket_client()` + for illustration purposes only. + These functions SHOULD NOT be used in a truly async program because each call + may take several seconds to complete and would block the EventLoop otherwise. + Additionally, the `fopen()` call will return a file handle on some platforms + which may or may not be supported by all EventLoop implementations. + As an alternative, you may want to use higher-level libraries listed above. + +### ReadableResourceStream + +The `ReadableResourceStream` is a concrete implementation of the +[`ReadableStreamInterface`](#readablestreaminterface) for PHP's stream resources. + +This can be used to represent a read-only resource like a file stream opened in +readable mode or a stream such as `STDIN`: + +```php +$stream = new ReadableResourceStream(STDIN); +$stream->on('data', function ($chunk) { + echo $chunk; +}); +$stream->on('end', function () { + echo 'END'; +}); +``` + +See also [`ReadableStreamInterface`](#readablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened in reading mode (e.g. `fopen()` mode `r`). +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new ReadableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDIN etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new ReadableResourceStream(STDIN); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$stream = new ReadableResourceStream(STDIN, null, 8192); +``` + +> PHP bug warning: If the PHP process has explicitly been started without a + `STDIN` stream, then trying to read from `STDIN` may return data from + another stream resource. This does not happen if you start this with an empty + stream like `php test.php < /dev/null` instead of `php test.php <&-`. + See [#81](https://github.com/reactphp/stream/issues/81) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### WritableResourceStream + +The `WritableResourceStream` is a concrete implementation of the +[`WritableStreamInterface`](#writablestreaminterface) for PHP's stream resources. + +This can be used to represent a write-only resource like a file stream opened in +writable mode or a stream such as `STDOUT` or `STDERR`: + +```php +$stream = new WritableResourceStream(STDOUT); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`WritableStreamInterface`](#writablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new WritableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new WritableResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $writeBufferSoftLimit` parameter that controls +this maximum buffer size in bytes. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +```php +$stream = new WritableResourceStream(STDOUT, null, 8192); +``` + +This class takes an optional `int|null $writeChunkSize` parameter that controls +this maximum buffer size in bytes to write at once to the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be written +at once to the underlying stream resource. Note that the actual number +of bytes written may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "write everything available" to the +underlying stream resource. + +```php +$stream = new WritableResourceStream(STDOUT, null, null, 8192); +``` + +See also [`write()`](#write) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### DuplexResourceStream + +The `DuplexResourceStream` is a concrete implementation of the +[`DuplexStreamInterface`](#duplexstreaminterface) for PHP's stream resources. + +This can be used to represent a read-and-write resource like a file stream opened +in read and write mode mode or a stream such as a TCP/IP connection: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`DuplexStreamInterface`](#duplexstreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for reading *and* writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new DuplexResourceStream(false); +``` + +See also the [`ReadableResourceStream`](#readableresourcestream) for read-only +and the [`WritableResourceStream`](#writableresourcestream) for write-only +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new DuplexResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn, null, 8192); +``` + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes another optional `WritableStreamInterface|null $buffer` parameter +that controls this write behavior of this stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +If you want to change the write buffer soft limit, you can pass an instance of +[`WritableResourceStream`](#writableresourcestream) like this: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$buffer = new WritableResourceStream($conn, null, 8192); +$stream = new DuplexResourceStream($conn, null, null, $buffer); +``` + +See also [`WritableResourceStream`](#writableresourcestream) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### ThroughStream + +The `ThroughStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and will simply pass any data +you write to it through to its readable end. + +```php +$through = new ThroughStream(); +$through->on('data', $this->expectCallableOnceWith('hello')); + +$through->write('hello'); +``` + +Similarly, the [`end()` method](#end) will end the stream and emit an +[`end` event](#end-event) and then [`close()`](#close-1) the stream. +The [`close()` method](#close-1) will close the stream and emit a +[`close` event](#close-event). +Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + +```php +$through = new ThroughStream(); +$source->pipe($through)->pipe($dest); +``` + +Optionally, its constructor accepts any callable function which will then be +used to *filter* any data written to it. This function receives a single data +argument as passed to the writable side and must return the data as it will be +passed to its readable end: + +```php +$through = new ThroughStream('strtoupper'); +$source->pipe($through)->pipe($dest); +``` + +Note that this class makes no assumptions about any data types. This can be +used to convert data, for example for transforming any structured data into +a newline-delimited JSON (NDJSON) stream like this: + +```php +$through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; +}); +$through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + +$through->write(array(2, true)); +``` + +The callback function is allowed to throw an `Exception`. In this case, +the stream will emit an `error` event and then [`close()`](#close-1) the stream. + +```php +$through = new ThroughStream(function ($data) { + if (!is_string($data)) { + throw new \UnexpectedValueException('Only strings allowed'); + } + return $data; +}); +$through->on('error', $this->expectCallableOnce())); +$through->on('close', $this->expectCallableOnce())); +$through->on('data', $this->expectCallableNever())); + +$through->write(2); +``` + +### CompositeStream + +The `CompositeStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and can be used to create a +single duplex stream from two individual streams implementing +[`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) respectively. + +This is useful for some APIs which may require a single +[`DuplexStreamInterface`](#duplexstreaminterface) or simply because it's often +more convenient to work with a single stream instance like this: + +```php +$stdin = new ReadableResourceStream(STDIN); +$stdout = new WritableResourceStream(STDOUT); + +$stdio = new CompositeStream($stdin, $stdout); + +$stdio->on('data', function ($chunk) use ($stdio) { + $stdio->write('You said: ' . $chunk); +}); +``` + +This is a well-behaving stream which forwards all stream events from the +underlying streams and forwards all streams calls to the underlying streams. + +If you `write()` to the duplex stream, it will simply `write()` to the +writable side and return its status. + +If you `end()` the duplex stream, it will `end()` the writable side and will +`pause()` the readable side. + +If you `close()` the duplex stream, both input streams will be closed. +If either of the two input streams emits a `close` event, the duplex stream +will also close. +If either of the two input streams is already closed while constructing the +duplex stream, it will `close()` the other side and return a closed stream. + +## Usage + +The following example can be used to pipe the contents of a source file into +a destination file without having to ever read the whole file into memory: + +```php +$source = new React\Stream\ReadableResourceStream(fopen('source.txt', 'r')); +$dest = new React\Stream\WritableResourceStream(fopen('destination.txt', 'w')); + +$source->pipe($dest); +``` + +> Note that this example uses `fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also [creating streams](#creating-streams) for more sophisticated + examples. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/stream:^1.4 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use PHP 7+* for this project due to its vast +performance improvements. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See [creating streams](#creating-streams) for more information on how streams + are created in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/stream/dependents) + for a list of packages that use streams in real-world applications. diff --git a/trilhas_poo/vendor/react/stream/composer.json b/trilhas_poo/vendor/react/stream/composer.json new file mode 100644 index 0000000..09d8b71 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/composer.json @@ -0,0 +1,47 @@ +{ + "name": "react/stream", + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": ["event-driven", "readable", "writable", "stream", "non-blocking", "io", "pipe", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.8", + "react/event-loop": "^1.2", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "clue/stream-filter": "~1.2" + }, + "autoload": { + "psr-4": { + "React\\Stream\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Stream\\": "tests/" + } + } +} diff --git a/trilhas_poo/vendor/react/stream/src/CompositeStream.php b/trilhas_poo/vendor/react/stream/src/CompositeStream.php new file mode 100644 index 0000000..dde091d --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/CompositeStream.php @@ -0,0 +1,83 @@ +readable = $readable; + $this->writable = $writable; + + if (!$readable->isReadable() || !$writable->isWritable()) { + $this->close(); + return; + } + + Util::forwardEvents($this->readable, $this, array('data', 'end', 'error')); + Util::forwardEvents($this->writable, $this, array('drain', 'error', 'pipe')); + + $this->readable->on('close', array($this, 'close')); + $this->writable->on('close', array($this, 'close')); + } + + public function isReadable() + { + return $this->readable->isReadable(); + } + + public function pause() + { + $this->readable->pause(); + } + + public function resume() + { + if (!$this->writable->isWritable()) { + return; + } + + $this->readable->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function isWritable() + { + return $this->writable->isWritable(); + } + + public function write($data) + { + return $this->writable->write($data); + } + + public function end($data = null) + { + $this->readable->pause(); + $this->writable->end($data); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->readable->close(); + $this->writable->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/trilhas_poo/vendor/react/stream/src/DuplexResourceStream.php b/trilhas_poo/vendor/react/stream/src/DuplexResourceStream.php new file mode 100644 index 0000000..d6de55c --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/DuplexResourceStream.php @@ -0,0 +1,240 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + + if ($buffer === null) { + $buffer = new WritableResourceStream($stream, $loop); + } + + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = ($readChunkSize === null) ? 65536 : (int)$readChunkSize; + $this->buffer = $buffer; + + $that = $this; + + $this->buffer->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + }); + + $this->buffer->on('close', array($this, 'close')); + + $this->buffer->on('drain', function () use ($that) { + $that->emit('drain'); + }); + + $this->resume(); + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = false; + } + } + + public function resume() + { + if (!$this->listening && $this->readable) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = true; + } + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + return $this->buffer->write($data); + } + + public function close() + { + if (!$this->writable && !$this->closing) { + return; + } + + $this->closing = false; + + $this->readable = false; + $this->writable = false; + + $this->emit('close'); + $this->pause(); + $this->buffer->close(); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + public function end($data = null) + { + if (!$this->writable) { + return; + } + + $this->closing = true; + + $this->readable = false; + $this->writable = false; + $this->pause(); + + $this->buffer->end($data); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + /** @internal */ + public function handleData($stream) + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) { + $error = new \ErrorException( + $errstr, + 0, + $errno, + $errfile, + $errline + ); + }); + + $data = \stream_get_contents($stream, $this->bufferSize); + + \restore_error_handler(); + + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) { + $meta = \stream_get_meta_data($resource); + + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return true; + } + } + return false; + } +} diff --git a/trilhas_poo/vendor/react/stream/src/DuplexStreamInterface.php b/trilhas_poo/vendor/react/stream/src/DuplexStreamInterface.php new file mode 100644 index 0000000..631ce31 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/DuplexStreamInterface.php @@ -0,0 +1,39 @@ + Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see ReadableStreamInterface + * @see WritableStreamInterface + */ +interface DuplexStreamInterface extends ReadableStreamInterface, WritableStreamInterface +{ +} diff --git a/trilhas_poo/vendor/react/stream/src/ReadableResourceStream.php b/trilhas_poo/vendor/react/stream/src/ReadableResourceStream.php new file mode 100644 index 0000000..823360a --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/ReadableResourceStream.php @@ -0,0 +1,188 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = ($readChunkSize === null) ? 65536 : (int)$readChunkSize; + + $this->resume(); + } + + public function isReadable() + { + return !$this->closed; + } + + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = false; + } + } + + public function resume() + { + if (!$this->listening && !$this->closed) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = true; + } + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + $this->emit('close'); + $this->pause(); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + /** @internal */ + public function handleData() + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) { + $error = new \ErrorException( + $errstr, + 0, + $errno, + $errfile, + $errline + ); + }); + + $data = \stream_get_contents($this->stream, $this->bufferSize); + + \restore_error_handler(); + + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) { + $meta = \stream_get_meta_data($resource); + + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return true; + } + } + return false; + } +} diff --git a/trilhas_poo/vendor/react/stream/src/ReadableStreamInterface.php b/trilhas_poo/vendor/react/stream/src/ReadableStreamInterface.php new file mode 100644 index 0000000..fa3d59c --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/ReadableStreamInterface.php @@ -0,0 +1,362 @@ +on('data', function ($data) { + * echo $data; + * }); + * ``` + * + * This event MAY be emitted any number of times, which may be zero times if + * this stream does not send any data at all. + * It SHOULD not be emitted after an `end` or `close` event. + * + * The given `$data` argument may be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit the raw (binary) payload data that is received over the wire as + * chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * end event: + * The `end` event will be emitted once the source stream has successfully + * reached the end of the stream (EOF). + * + * ```php + * $stream->on('end', function () { + * echo 'END'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * a successful end was detected. + * It SHOULD NOT be emitted after a previous `end` or `close` event. + * It MUST NOT be emitted if the stream closes due to a non-successful + * end, such as after a previous `error` event. + * + * After the stream is ended, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * This event will only be emitted if the *end* was reached successfully, + * not if the stream was interrupted by an unrecoverable error or explicitly + * closed. Not all streams know this concept of a "successful end". + * Many use-cases involve detecting when the stream closes (terminates) + * instead, in this case you should use the `close` event. + * After the stream emits an `end` event, it SHOULD usually be followed by a + * `close` event. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit this event if either the remote side closes the connection or + * a file handle was successfully read until reaching its end (EOF). + * + * Note that this event should not be confused with the `end()` method. + * This event defines a successful end *reading* from a source stream, while + * the `end()` method defines *writing* a successful end to a destination + * stream. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to read from this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error or after an unexpected `data` or premature + * `end` event. + * It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-readable mode, see + * also `close()` and `isReadable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and do not make assumption about data + * boundaries (such as unexpected `data` or premature `end` events). + * In other words, many lower-level protocols (such as TCP/IP) may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * Unlike the `end` event, this event SHOULD be emitted whenever the stream + * closes, irrespective of whether this happens implicitly due to an + * unrecoverable error or explicitly when either side closes the stream. + * If you only want to detect a *successful* end, you should use the `end` + * event instead. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after reading a *successful* `end` + * event or after a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + */ +interface ReadableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a readable state (not closed already). + * + * This method can be used to check if the stream still accepts incoming + * data events or if it is ended or closed already. + * Once the stream is non-readable, no further `data` or `end` events SHOULD + * be emitted. + * + * ```php + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * A successfully opened stream always MUST start in readable mode. + * + * Once the stream ends or closes, it MUST switch to non-readable mode. + * This can happen any time, explicitly through `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-readable mode, it MUST NOT transition + * back to readable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `isWritable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isReadable(); + + /** + * Pauses reading incoming data events. + * + * Removes the data source file descriptor from the event loop. This + * allows you to throttle incoming data. + * + * Unless otherwise noted, a successfully opened stream SHOULD NOT start + * in paused state. + * + * Once the stream is paused, no futher `data` or `end` events SHOULD + * be emitted. + * + * ```php + * $stream->pause(); + * + * $stream->on('data', assertShouldNeverCalled()); + * $stream->on('end', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * stream MAY continue emitting `data` events. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * + * @see self::resume() + * @return void + */ + public function pause(); + + /** + * Resumes reading incoming data events. + * + * Re-attach the data source after a previous `pause()`. + * + * ```php + * $stream->pause(); + * + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * + * @see self::pause() + * @return void + */ + public function resume(); + + /** + * Pipes all the data from this readable source into the given writable destination. + * + * Automatically sends all incoming data to the destination. + * Automatically throttles the source based on what the destination can handle. + * + * ```php + * $source->pipe($dest); + * ``` + * + * Similarly, you can also pipe an instance implementing `DuplexStreamInterface` + * into itself in order to write back all the data that is received. + * This may be a useful feature for a TCP/IP echo service: + * + * ```php + * $connection->pipe($connection); + * ``` + * + * This method returns the destination stream as-is, which can be used to + * set up chains of piped streams: + * + * ```php + * $source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); + * ``` + * + * By default, this will call `end()` on the destination stream once the + * source stream emits an `end` event. This can be disabled like this: + * + * ```php + * $source->pipe($dest, array('end' => false)); + * ``` + * + * Note that this only applies to the `end` event. + * If an `error` or explicit `close` event happens on the source stream, + * you'll have to manually close the destination stream: + * + * ```php + * $source->pipe($dest); + * $source->on('close', function () use ($dest) { + * $dest->end('BYE!'); + * }); + * ``` + * + * If the source stream is not readable (closed state), then this is a NO-OP. + * + * ```php + * $source->close(); + * $source->pipe($dest); // NO-OP + * ``` + * + * If the destinantion stream is not writable (closed state), then this will simply + * throttle (pause) the source stream: + * + * ```php + * $dest->close(); + * $source->pipe($dest); // calls $source->pause() + * ``` + * + * Similarly, if the destination stream is closed while the pipe is still + * active, it will also throttle (pause) the source stream: + * + * ```php + * $source->pipe($dest); + * $dest->close(); // calls $source->pause() + * ``` + * + * Once the pipe is set up successfully, the destination stream MUST emit + * a `pipe` event with this source stream an event argument. + * + * @param WritableStreamInterface $dest + * @param array $options + * @return WritableStreamInterface $dest stream as-is + */ + public function pipe(WritableStreamInterface $dest, array $options = array()); + + /** + * Closes the stream (forcefully). + * + * This method can be used to (forcefully) close the stream. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-readable + * mode, see also `isReadable()`. + * This means that no further `data` or `end` events SHOULD be emitted. + * + * ```php + * $stream->close(); + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this method should not be confused with the `end()` method. + * + * @return void + * @see WritableStreamInterface::close() + */ + public function close(); +} diff --git a/trilhas_poo/vendor/react/stream/src/ThroughStream.php b/trilhas_poo/vendor/react/stream/src/ThroughStream.php new file mode 100644 index 0000000..3b4fbb7 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/ThroughStream.php @@ -0,0 +1,195 @@ +on('data', $this->expectCallableOnceWith('hello')); + * + * $through->write('hello'); + * ``` + * + * Similarly, the [`end()` method](#end) will end the stream and emit an + * [`end` event](#end-event) and then [`close()`](#close-1) the stream. + * The [`close()` method](#close-1) will close the stream and emit a + * [`close` event](#close-event). + * Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + * + * ```php + * $through = new ThroughStream(); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Optionally, its constructor accepts any callable function which will then be + * used to *filter* any data written to it. This function receives a single data + * argument as passed to the writable side and must return the data as it will be + * passed to its readable end: + * + * ```php + * $through = new ThroughStream('strtoupper'); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Note that this class makes no assumptions about any data types. This can be + * used to convert data, for example for transforming any structured data into + * a newline-delimited JSON (NDJSON) stream like this: + * + * ```php + * $through = new ThroughStream(function ($data) { + * return json_encode($data) . PHP_EOL; + * }); + * $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + * + * $through->write(array(2, true)); + * ``` + * + * The callback function is allowed to throw an `Exception`. In this case, + * the stream will emit an `error` event and then [`close()`](#close-1) the stream. + * + * ```php + * $through = new ThroughStream(function ($data) { + * if (!is_string($data)) { + * throw new \UnexpectedValueException('Only strings allowed'); + * } + * return $data; + * }); + * $through->on('error', $this->expectCallableOnce())); + * $through->on('close', $this->expectCallableOnce())); + * $through->on('data', $this->expectCallableNever())); + * + * $through->write(2); + * ``` + * + * @see WritableStreamInterface::write() + * @see WritableStreamInterface::end() + * @see DuplexStreamInterface::close() + * @see WritableStreamInterface::pipe() + */ +final class ThroughStream extends EventEmitter implements DuplexStreamInterface +{ + private $readable = true; + private $writable = true; + private $closed = false; + private $paused = false; + private $drain = false; + private $callback; + + public function __construct($callback = null) + { + if ($callback !== null && !\is_callable($callback)) { + throw new InvalidArgumentException('Invalid transformation callback given'); + } + + $this->callback = $callback; + } + + public function pause() + { + // only allow pause if still readable, false otherwise + $this->paused = $this->readable; + } + + public function resume() + { + $this->paused = false; + + // emit drain event if previous write was paused (throttled) + if ($this->drain) { + $this->drain = false; + $this->emit('drain'); + } + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + if ($this->callback !== null) { + try { + $data = \call_user_func($this->callback, $data); + } catch (\Exception $e) { + $this->emit('error', array($e)); + $this->close(); + + return false; + } + } + + $this->emit('data', array($data)); + + // emit drain event on next resume if currently paused (throttled) + if ($this->paused) { + $this->drain = true; + } + + // continue writing if still writable and not paused (throttled), false otherwise + return $this->writable && !$this->paused; + } + + public function end($data = null) + { + if (!$this->writable) { + return; + } + + if (null !== $data) { + $this->write($data); + + // return if write() already caused the stream to close + if (!$this->writable) { + return; + } + } + + $this->readable = false; + $this->writable = false; + $this->paused = false; + $this->drain = false; + + $this->emit('end'); + $this->close(); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->readable = false; + $this->writable = false; + $this->paused = false; + $this->drain = false; + + $this->closed = true; + $this->callback = null; + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/trilhas_poo/vendor/react/stream/src/Util.php b/trilhas_poo/vendor/react/stream/src/Util.php new file mode 100644 index 0000000..056b037 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/Util.php @@ -0,0 +1,75 @@ + NO-OP + if (!$source->isReadable()) { + return $dest; + } + + // destination not writable => just pause() source + if (!$dest->isWritable()) { + $source->pause(); + + return $dest; + } + + $dest->emit('pipe', array($source)); + + // forward all source data events as $dest->write() + $source->on('data', $dataer = function ($data) use ($source, $dest) { + $feedMore = $dest->write($data); + + if (false === $feedMore) { + $source->pause(); + } + }); + $dest->on('close', function () use ($source, $dataer) { + $source->removeListener('data', $dataer); + $source->pause(); + }); + + // forward destination drain as $source->resume() + $dest->on('drain', $drainer = function () use ($source) { + $source->resume(); + }); + $source->on('close', function () use ($dest, $drainer) { + $dest->removeListener('drain', $drainer); + }); + + // forward end event from source as $dest->end() + $end = isset($options['end']) ? $options['end'] : true; + if ($end) { + $source->on('end', $ender = function () use ($dest) { + $dest->end(); + }); + $dest->on('close', function () use ($source, $ender) { + $source->removeListener('end', $ender); + }); + } + + return $dest; + } + + public static function forwardEvents($source, $target, array $events) + { + foreach ($events as $event) { + $source->on($event, function () use ($event, $target) { + $target->emit($event, \func_get_args()); + }); + } + } +} diff --git a/trilhas_poo/vendor/react/stream/src/WritableResourceStream.php b/trilhas_poo/vendor/react/stream/src/WritableResourceStream.php new file mode 100644 index 0000000..e3a7e74 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/WritableResourceStream.php @@ -0,0 +1,178 @@ +stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->softLimit = ($writeBufferSoftLimit === null) ? 65536 : (int)$writeBufferSoftLimit; + $this->writeChunkSize = ($writeChunkSize === null) ? -1 : (int)$writeChunkSize; + } + + public function isWritable() + { + return $this->writable; + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + $this->data .= $data; + + if (!$this->listening && $this->data !== '') { + $this->listening = true; + + $this->loop->addWriteStream($this->stream, array($this, 'handleWrite')); + } + + return !isset($this->data[$this->softLimit - 1]); + } + + public function end($data = null) + { + if (null !== $data) { + $this->write($data); + } + + $this->writable = false; + + // close immediately if buffer is already empty + // otherwise wait for buffer to flush first + if ($this->data === '') { + $this->close(); + } + } + + public function close() + { + if ($this->closed) { + return; + } + + if ($this->listening) { + $this->listening = false; + $this->loop->removeWriteStream($this->stream); + } + + $this->closed = true; + $this->writable = false; + $this->data = ''; + + $this->emit('close'); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + /** @internal */ + public function handleWrite() + { + $error = null; + \set_error_handler(function ($_, $errstr) use (&$error) { + $error = $errstr; + }); + + if ($this->writeChunkSize === -1) { + $sent = \fwrite($this->stream, $this->data); + } else { + $sent = \fwrite($this->stream, $this->data, $this->writeChunkSize); + } + + \restore_error_handler(); + + // Only report errors if *nothing* could be sent and an error has been raised. + // Ignore non-fatal warnings if *some* data could be sent. + // Any hard (permanent) error will fail to send any data at all. + // Sending excessive amounts of data will only flush *some* data and then + // report a temporary error (EAGAIN) which we do not raise here in order + // to keep the stream open for further tries to write. + // Should this turn out to be a permanent error later, it will eventually + // send *nothing* and we can detect this. + if (($sent === 0 || $sent === false) && $error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to write to stream: ' . $error))); + $this->close(); + + return; + } + + $exceeded = isset($this->data[$this->softLimit - 1]); + $this->data = (string) \substr($this->data, $sent); + + // buffer has been above limit and is now below limit + if ($exceeded && !isset($this->data[$this->softLimit - 1])) { + $this->emit('drain'); + } + + // buffer is now completely empty => stop trying to write + if ($this->data === '') { + // stop waiting for resource to be writable + if ($this->listening) { + $this->loop->removeWriteStream($this->stream); + $this->listening = false; + } + + // buffer is end()ing and now completely empty => close buffer + if (!$this->writable) { + $this->close(); + } + } + } +} diff --git a/trilhas_poo/vendor/react/stream/src/WritableStreamInterface.php b/trilhas_poo/vendor/react/stream/src/WritableStreamInterface.php new file mode 100644 index 0000000..e262592 --- /dev/null +++ b/trilhas_poo/vendor/react/stream/src/WritableStreamInterface.php @@ -0,0 +1,347 @@ +on('drain', function () use ($stream) { + * echo 'Stream is now ready to accept more data'; + * }); + * ``` + * + * This event SHOULD be emitted once every time the buffer became full + * previously and is now ready to accept more data. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if the buffer never became full in the first place. + * This event SHOULD NOT be emitted if the buffer has not become full + * previously. + * + * This event is mostly used internally, see also `write()` for more details. + * + * pipe event: + * The `pipe` event will be emitted whenever a readable stream is `pipe()`d + * into this stream. + * The event receives a single `ReadableStreamInterface` argument for the + * source stream. + * + * ```php + * $stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + * echo 'Now receiving piped data'; + * + * // explicitly close target if source emits an error + * $source->on('error', function () use ($stream) { + * $stream->close(); + * }); + * }); + * + * $source->pipe($stream); + * ``` + * + * This event MUST be emitted once for each readable stream that is + * successfully piped into this destination stream. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if no stream is ever piped into this stream. + * This event MUST NOT be emitted if either the source is not readable + * (closed already) or this destination is not writable (closed already). + * + * This event is mostly used internally, see also `pipe()` for more details. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to write to this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error. + * It SHOULD NOT be emitted after a previous `error` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-writable mode, see + * also `close()` and `isWritable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-writable mode, + * see also `isWritable()`. + * + * This event SHOULD be emitted whenever the stream closes, irrespective of + * whether this happens implicitly due to an unrecoverable error or + * explicitly when either side closes the stream. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after flushing the buffer from + * the `end()` method, after receiving a *successful* `end` event or after + * a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + * @see DuplexStreamInterface + */ +interface WritableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a writable state (not closed already). + * + * This method can be used to check if the stream still accepts writing + * any data or if it is ended or closed already. + * Writing any data to a non-writable stream is a NO-OP: + * + * ```php + * assert($stream->isWritable() === false); + * + * $stream->write('end'); // NO-OP + * $stream->end('end'); // NO-OP + * ``` + * + * A successfully opened stream always MUST start in writable mode. + * + * Once the stream ends or closes, it MUST switch to non-writable mode. + * This can happen any time, explicitly through `end()` or `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-writable mode, it MUST NOT transition + * back to writable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `isReadable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isWritable(); + + /** + * Write some data into the stream. + * + * A successful write MUST be confirmed with a boolean `true`, which means + * that either the data was written (flushed) immediately or is buffered and + * scheduled for a future write. Note that this interface gives you no + * control over explicitly flushing the buffered data, as finding the + * appropriate time for this is beyond the scope of this interface and left + * up to the implementation of this interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * If a stream cannot handle writing (or flushing) the data, it SHOULD emit + * an `error` event and MAY `close()` the stream if it can not recover from + * this error. + * + * If the internal buffer is full after adding `$data`, then `write()` + * SHOULD return `false`, indicating that the caller should stop sending + * data until the buffer drains. + * The stream SHOULD send a `drain` event once the buffer is ready to accept + * more data. + * + * Similarly, if the stream is not writable (already in a closed state) + * it MUST NOT process the given `$data` and SHOULD return `false`, + * indicating that the caller should stop sending data. + * + * The given `$data` argument MAY be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will only accept the raw (binary) payload data that is transferred over + * the wire as chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * @param mixed|string $data + * @return bool + */ + public function write($data); + + /** + * Successfully ends the stream (after optionally sending some final data). + * + * This method can be used to successfully end the stream, i.e. close + * the stream after sending out all data that is currently buffered. + * + * ```php + * $stream->write('hello'); + * $stream->write('world'); + * $stream->end(); + * ``` + * + * If there's no data currently buffered and nothing to be flushed, then + * this method MAY `close()` the stream immediately. + * + * If there's still data in the buffer that needs to be flushed first, then + * this method SHOULD try to write out this data and only then `close()` + * the stream. + * Once the stream is closed, it SHOULD emit a `close` event. + * + * Note that this interface gives you no control over explicitly flushing + * the buffered data, as finding the appropriate time for this is beyond the + * scope of this interface and left up to the implementation of this + * interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * You can optionally pass some final data that is written to the stream + * before ending the stream. If a non-`null` value is given as `$data`, then + * this method will behave just like calling `write($data)` before ending + * with no data. + * + * ```php + * // shorter version + * $stream->end('bye'); + * + * // same as longer version + * $stream->write('bye'); + * $stream->end(); + * ``` + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->end(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * If this stream is a `DuplexStreamInterface`, calling this method SHOULD + * also end its readable side, unless the stream supports half-open mode. + * In other words, after calling this method, these streams SHOULD switch + * into non-writable AND non-readable mode, see also `isReadable()`. + * This implies that in this case, the stream SHOULD NOT emit any `data` + * or `end` events anymore. + * Streams MAY choose to use the `pause()` method logic for this, but + * special care may have to be taken to ensure a following call to the + * `resume()` method SHOULD NOT continue emitting readable events. + * + * Note that this method should not be confused with the `close()` method. + * + * @param mixed|string|null $data + * @return void + */ + public function end($data = null); + + /** + * Closes the stream (forcefully). + * + * This method can be used to forcefully close the stream, i.e. close + * the stream without waiting for any buffered data to be flushed. + * If there's still data in the buffer, this data SHOULD be discarded. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->close(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * Note that this method should not be confused with the `end()` method. + * Unlike the `end()` method, this method does not take care of any existing + * buffers and simply discards any buffer contents. + * Likewise, this method may also be called after calling `end()` on a + * stream in order to stop waiting for the stream to flush its final data. + * + * ```php + * $stream->end(); + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->close(); + * }); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * + * @return void + * @see ReadableStreamInterface::close() + */ + public function close(); +} diff --git a/trilhas_poo/vendor/sebastian/diff/ChangeLog.md b/trilhas_poo/vendor/sebastian/diff/ChangeLog.md new file mode 100644 index 0000000..5e9fe25 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/ChangeLog.md @@ -0,0 +1,236 @@ +# ChangeLog + +All notable changes are documented in this file using the [Keep a CHANGELOG](http://keepachangelog.com/) principles. + +## [9.0.0] - 2026-06-05 + +### Changed + +* [#138](https://github.com/sebastianbergmann/diff/pull/138): Use Eugene W. Myers' linear-space algorithm + +### Removed + +* [#157](https://github.com/sebastianbergmann/diff/issues/157): The `UnifiedDiffOutputBuilder` and `AbstractChunkOutputBuilder` classes have been removed, use `StrictUnifiedDiffOutputBuilder` instead +* The `SebastianBergmann\Diff\LongestCommonSubsequenceCalculator` interface, its two implementations `SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator` and `SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator`, and the `$lcs` parameter of `SebastianBergmann\Diff\Differ::diff()` and `SebastianBergmann\Diff\Differ::diffToArray()` have been removed + +## [8.3.0] - 2026-05-15 + +### Added + +* [#136](https://github.com/sebastianbergmann/diff/issues/136): `UnifiedDiffOutputBuilder` now accepts a fourth `$emitNoLineEndEofWarning` constructor parameter (default `true`) to suppress the `\ No newline at end of file` marker for use cases such as PHPUnit comparison failures that are not related to files +* [#136](https://github.com/sebastianbergmann/diff/issues/136): `StrictUnifiedDiffOutputBuilder` now accepts the options `addLineNumbers`, `emitDiffLineEndWarning`, `emitNoLineEndEofWarning`, and `header` + +### Changed + +* [#136](https://github.com/sebastianbergmann/diff/issues/136): `UnifiedDiffOutputBuilder` now returns an empty string when no difference is detected (previously: returned the header) +* [#136](https://github.com/sebastianbergmann/diff/issues/136): `UnifiedDiffOutputBuilder::writeHunk()` now writes the actual `\ No newline at end of file` marker text (previously: wrote only a line break) and silently skips diff entries with unknown types + +### Deprecated + +* The `SebastianBergmann\Diff\LongestCommonSubsequenceCalculator` interface, its two implementations `SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator` and `SebastianBergmann\Diff\MemoryEfficientLongestCommonSubsequenceCalculator`, and the `$lcs` parameter of `SebastianBergmann\Diff\Differ::diff()` and `SebastianBergmann\Diff\Differ::diffToArray()` are now deprecated; do not pass the `$lcs` parameter any more in preparation for the removal of these symbols and this parameter, respectively + +## [8.2.1] - 2026-05-14 + +### Changed + +* [#136](https://github.com/sebastianbergmann/diff/issues/136): Reverted changes introduced in version 8.2.0 + +## [8.2.0] - 2026-05-14 + +### Changed + +* [#136](https://github.com/sebastianbergmann/diff/issues/136): Align `UnifiedDiffOutputBuilder` behavior with `StrictUnifiedDiffOutputBuilder` + +## [8.1.0] - 2026-04-05 + +### Added + +* [#135](https://github.com/sebastianbergmann/diff/issues/135): Add `$contextLines` constructor parameter on `UnifiedDiffOutputBuilder` + +## [8.0.0] - 2026-02-06 + +### Removed + +* This component is no longer supported on PHP 8.3 + +## [7.0.0] - 2025-02-07 + +### Removed + +* This component is no longer supported on PHP 8.2 + +## [6.0.2] - 2024-07-03 + +### Changed + +* This project now uses PHPStan instead of Psalm for static analysis + +## [6.0.1] - 2024-03-02 + +### Changed + +* Do not use implicitly nullable parameters + +## [6.0.0] - 2024-02-02 + +### Removed + +* `SebastianBergmann\Diff\Chunk::getStart()`, `SebastianBergmann\Diff\Chunk::getStartRange()`, `SebastianBergmann\Diff\Chunk::getEnd()`, `SebastianBergmann\Diff\Chunk::getEndRange()`, and `SebastianBergmann\Diff\Chunk::getLines()` +* `SebastianBergmann\Diff\Diff::getFrom()`, `SebastianBergmann\Diff\Diff::getTo()`, and `SebastianBergmann\Diff\Diff::getChunks()` +* `SebastianBergmann\Diff\Line::getContent()` and `SebastianBergmann\Diff\Diff::getType()` +* This component is no longer supported on PHP 8.1 + +## [5.1.1] - 2024-03-02 + +### Changed + +* Do not use implicitly nullable parameters + +## [5.1.0] - 2023-12-22 + +### Added + +* `SebastianBergmann\Diff\Chunk::start()`, `SebastianBergmann\Diff\Chunk::startRange()`, `SebastianBergmann\Diff\Chunk::end()`, `SebastianBergmann\Diff\Chunk::endRange()`, and `SebastianBergmann\Diff\Chunk::lines()` +* `SebastianBergmann\Diff\Diff::from()`, `SebastianBergmann\Diff\Diff::to()`, and `SebastianBergmann\Diff\Diff::chunks()` +* `SebastianBergmann\Diff\Line::content()` and `SebastianBergmann\Diff\Diff::type()` +* `SebastianBergmann\Diff\Line::isAdded()`,`SebastianBergmann\Diff\Line::isRemoved()`, and `SebastianBergmann\Diff\Line::isUnchanged()` + +### Changed + +* `SebastianBergmann\Diff\Diff` now implements `IteratorAggregate`, iterating over it yields the aggregated `SebastianBergmann\Diff\Chunk` objects +* `SebastianBergmann\Diff\Chunk` now implements `IteratorAggregate`, iterating over it yields the aggregated `SebastianBergmann\Diff\Line` objects + +### Deprecated + +* `SebastianBergmann\Diff\Chunk::getStart()`, `SebastianBergmann\Diff\Chunk::getStartRange()`, `SebastianBergmann\Diff\Chunk::getEnd()`, `SebastianBergmann\Diff\Chunk::getEndRange()`, and `SebastianBergmann\Diff\Chunk::getLines()` +* `SebastianBergmann\Diff\Diff::getFrom()`, `SebastianBergmann\Diff\Diff::getTo()`, and `SebastianBergmann\Diff\Diff::getChunks()` +* `SebastianBergmann\Diff\Line::getContent()` and `SebastianBergmann\Diff\Diff::getType()` + +## [5.0.3] - 2023-05-01 + +### Changed + +* [#119](https://github.com/sebastianbergmann/diff/pull/119): Improve performance of `TimeEfficientLongestCommonSubsequenceCalculator` + +## [5.0.2] - 2023-05-01 + +### Changed + +* [#118](https://github.com/sebastianbergmann/diff/pull/118): Improve performance of `MemoryEfficientLongestCommonSubsequenceCalculator` + +## [5.0.1] - 2023-03-23 + +### Fixed + +* [#115](https://github.com/sebastianbergmann/diff/pull/115): `Parser::parseFileDiff()` does not handle diffs correctly that only add lines or only remove lines + +## [5.0.0] - 2023-02-03 + +### Changed + +* Passing a `DiffOutputBuilderInterface` instance to `Differ::__construct()` is no longer optional + +### Removed + +* This component is no longer supported on PHP 7.3, PHP 7.4, and PHP 8.0 + +## [4.0.4] - 2020-10-26 + +### Fixed + +* `SebastianBergmann\Diff\Exception` now correctly extends `\Throwable` + +## [4.0.3] - 2020-09-28 + +### Changed + +* Changed PHP version constraint in `composer.json` from `^7.3 || ^8.0` to `>=7.3` + +## [4.0.2] - 2020-06-30 + +### Added + +* This component is now supported on PHP 8 + +## [4.0.1] - 2020-05-08 + +### Fixed + +* [#99](https://github.com/sebastianbergmann/diff/pull/99): Regression in unified diff output of identical strings + +## [4.0.0] - 2020-02-07 + +### Removed + +* This component is no longer supported on PHP 7.1 and PHP 7.2 + +## [3.0.2] - 2019-02-04 + +### Changed + +* `Chunk::setLines()` now ensures that the `$lines` array only contains `Line` objects + +## [3.0.1] - 2018-06-10 + +### Fixed + +* Removed `"minimum-stability": "dev",` from `composer.json` + +## [3.0.0] - 2018-02-01 + +* The `StrictUnifiedDiffOutputBuilder` implementation of the `DiffOutputBuilderInterface` was added + +### Changed + +* The default `DiffOutputBuilderInterface` implementation now generates context lines (unchanged lines) + +### Removed + +* This component is no longer supported on PHP 7.0 + +### Fixed + +* [#70](https://github.com/sebastianbergmann/diff/issues/70): Diffing of arrays no longer works + +## [2.0.1] - 2017-08-03 + +### Fixed + +* [#66](https://github.com/sebastianbergmann/diff/pull/66): Restored backwards compatibility for PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3 + +## [2.0.0] - 2017-07-11 [YANKED] + +### Added + +* [#64](https://github.com/sebastianbergmann/diff/pull/64): Show line numbers for chunks of a diff + +### Removed + +* This component is no longer supported on PHP 5.6 + +[9.0.0]: https://github.com/sebastianbergmann/diff/compare/8.3.0...9.0.0 +[8.3.0]: https://github.com/sebastianbergmann/diff/compare/8.2.1...8.3.0 +[8.2.1]: https://github.com/sebastianbergmann/diff/compare/8.2.0...8.2.1 +[8.2.0]: https://github.com/sebastianbergmann/diff/compare/8.1.0...8.2.0 +[8.1.0]: https://github.com/sebastianbergmann/diff/compare/8.0.0...8.1.0 +[8.0.0]: https://github.com/sebastianbergmann/diff/compare/7.0...8.0.0 +[7.0.0]: https://github.com/sebastianbergmann/diff/compare/6.0.2...7.0.0 +[6.0.2]: https://github.com/sebastianbergmann/diff/compare/6.0.1...6.0.2 +[6.0.1]: https://github.com/sebastianbergmann/diff/compare/6.0.0...6.0.1 +[6.0.0]: https://github.com/sebastianbergmann/diff/compare/5.1...6.0.0 +[5.1.1]: https://github.com/sebastianbergmann/diff/compare/5.1.0...5.1.1 +[5.1.0]: https://github.com/sebastianbergmann/diff/compare/5.0.3...5.1.0 +[5.0.3]: https://github.com/sebastianbergmann/diff/compare/5.0.2...5.0.3 +[5.0.2]: https://github.com/sebastianbergmann/diff/compare/5.0.1...5.0.2 +[5.0.1]: https://github.com/sebastianbergmann/diff/compare/5.0.0...5.0.1 +[5.0.0]: https://github.com/sebastianbergmann/diff/compare/4.0.4...5.0.0 +[4.0.4]: https://github.com/sebastianbergmann/diff/compare/4.0.3...4.0.4 +[4.0.3]: https://github.com/sebastianbergmann/diff/compare/4.0.2...4.0.3 +[4.0.2]: https://github.com/sebastianbergmann/diff/compare/4.0.1...4.0.2 +[4.0.1]: https://github.com/sebastianbergmann/diff/compare/4.0.0...4.0.1 +[4.0.0]: https://github.com/sebastianbergmann/diff/compare/3.0.2...4.0.0 +[3.0.2]: https://github.com/sebastianbergmann/diff/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/sebastianbergmann/diff/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/sebastianbergmann/diff/compare/2.0...3.0.0 +[2.0.1]: https://github.com/sebastianbergmann/diff/compare/c341c98ce083db77f896a0aa64f5ee7652915970...2.0.1 +[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.4...c341c98ce083db77f896a0aa64f5ee7652915970 diff --git a/trilhas_poo/vendor/sebastian/diff/LICENSE b/trilhas_poo/vendor/sebastian/diff/LICENSE new file mode 100644 index 0000000..0fad16f --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2002-2026, Sebastian Bergmann +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/trilhas_poo/vendor/sebastian/diff/README.md b/trilhas_poo/vendor/sebastian/diff/README.md new file mode 100644 index 0000000..6688692 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/README.md @@ -0,0 +1,151 @@ +[![Latest Stable Version](https://poser.pugx.org/sebastian/diff/v)](https://packagist.org/packages/sebastian/diff) +[![CI Status](https://github.com/sebastianbergmann/diff/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/diff/actions) +[![codecov](https://codecov.io/gh/sebastianbergmann/diff/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/diff) + +# sebastian/diff + +Diff implementation for PHP, factored out of PHPUnit into a stand-alone component. + +## Installation + +You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/): + +``` +composer require sebastian/diff +``` + +If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency: + +``` +composer require --dev sebastian/diff +``` + +### Usage + +#### Generating diff + +The `Differ` class can be used to generate a textual representation of the difference between two strings: + +```php +diff('foo', 'bar'); +``` + +The code above yields the output below: + +```diff +--- Original ++++ New +@@ @@ +-foo ++bar +``` + +The `UnifiedDiffOutputBuilder` used in the example above generates output in "unified diff" +format and is used by PHPUnit, for example. + +The `StrictUnifiedDiffOutputBuilder` generates output in "strict unified diff" format with +hunks, similar to `diff -u` and compatible with `patch` or `git apply`. + +The `DiffOnlyOutputBuilder` generates output that only contains the lines that differ. + +If none of these three output builders match your use case then you can implement +`DiffOutputBuilderInterface` to generate custom output. + +#### Parsing diff + +The `Parser` class can be used to parse a unified diff into an object graph: + +```php +use SebastianBergmann\Diff\Parser; +use SebastianBergmann\Git; + +$git = new Git('/usr/local/src/money'); + +$diff = $git->getDiff( + '948a1a07768d8edd10dcefa8315c1cbeffb31833', + 'c07a373d2399f3e686234c4f7f088d635eb9641b' +); + +$parser = new Parser; + +print_r($parser->parse($diff)); +``` + +The code above yields the output below: + + Array + ( + [0] => SebastianBergmann\Diff\Diff Object + ( + [from:SebastianBergmann\Diff\Diff:private] => a/tests/MoneyTest.php + [to:SebastianBergmann\Diff\Diff:private] => b/tests/MoneyTest.php + [chunks:SebastianBergmann\Diff\Diff:private] => Array + ( + [0] => SebastianBergmann\Diff\Chunk Object + ( + [start:SebastianBergmann\Diff\Chunk:private] => 87 + [startRange:SebastianBergmann\Diff\Chunk:private] => 7 + [end:SebastianBergmann\Diff\Chunk:private] => 87 + [endRange:SebastianBergmann\Diff\Chunk:private] => 7 + [lines:SebastianBergmann\Diff\Chunk:private] => Array + ( + [0] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::add + ) + + [1] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::newMoney + ) + + [2] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => */ + ) + + [3] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 2 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyWithSameCurrencyObjectCanBeAdded() + ) + + [4] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 1 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyObjectWithSameCurrencyCanBeAdded() + ) + + [5] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => { + ) + + [6] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $a = new Money(1, new Currency('EUR')); + ) + + [7] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $b = new Money(2, new Currency('EUR')); + ) + ) + ) + ) + ) + ) + +Note: If the chunk size is 0 lines, i.e., `getStartRange()` or `getEndRange()` return 0, the number of line returned by `getStart()` or `getEnd()` is one lower than one would expect. It is the line number after which the chunk should be inserted or deleted; in all other cases, it gives the first line number of the replaced range of lines. diff --git a/trilhas_poo/vendor/sebastian/diff/SECURITY.md b/trilhas_poo/vendor/sebastian/diff/SECURITY.md new file mode 100644 index 0000000..af0c5a4 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/SECURITY.md @@ -0,0 +1,10 @@ +# Security Policy + +The library that is developed in this repository is a first-party dependency of [PHPUnit](https://github.com/sebastianbergmann/phpunit). +[PHPUnit's Security Policy](https://github.com/sebastianbergmann/phpunit/security/policy) applies to this library as well. + +If you believe you have found a security vulnerability in this library, please report it to me through coordinated disclosure. + +Use my [PGP key](https://sebastian-bergmann.de/gpg.asc) for encrypted email, for example when your report includes proof-of-concept exploits against third-party systems. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** diff --git a/trilhas_poo/vendor/sebastian/diff/composer.json b/trilhas_poo/vendor/sebastian/diff/composer.json new file mode 100644 index 0000000..7e18bca --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/composer.json @@ -0,0 +1,51 @@ +{ + "name": "sebastian/diff", + "description": "Diff implementation", + "keywords": ["diff", "udiff", "unidiff", "unified diff"], + "homepage": "https://github.com/sebastianbergmann/diff", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy" + }, + "prefer-stable": true, + "config": { + "platform": { + "php": "8.4.1" + }, + "optimize-autoloader": true, + "sort-packages": true + }, + "require": { + "php": ">=8.4" + }, + "require-dev": { + "phpunit/phpunit": "^13.2", + "symfony/process": "^7.4.13" + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "autoload-dev": { + "classmap": [ + "tests/" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "9.0-dev" + } + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Chunk.php b/trilhas_poo/vendor/sebastian/diff/src/Chunk.php new file mode 100644 index 0000000..18b5ce1 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Chunk.php @@ -0,0 +1,83 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use ArrayIterator; +use IteratorAggregate; +use Traversable; + +/** + * @template-implements IteratorAggregate + */ +final class Chunk implements IteratorAggregate +{ + private int $start; + private int $startRange; + private int $end; + private int $endRange; + + /** + * @var list + */ + private array $lines; + + /** + * @param list $lines + */ + public function __construct(int $start = 0, int $startRange = 1, int $end = 0, int $endRange = 1, array $lines = []) + { + $this->start = $start; + $this->startRange = $startRange; + $this->end = $end; + $this->endRange = $endRange; + $this->lines = $lines; + } + + public function start(): int + { + return $this->start; + } + + public function startRange(): int + { + return $this->startRange; + } + + public function end(): int + { + return $this->end; + } + + public function endRange(): int + { + return $this->endRange; + } + + /** + * @return list + */ + public function lines(): array + { + return $this->lines; + } + + /** + * @param list $lines + */ + public function setLines(array $lines): void + { + $this->lines = $lines; + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->lines); + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Diff.php b/trilhas_poo/vendor/sebastian/diff/src/Diff.php new file mode 100644 index 0000000..372eb3d --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Diff.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use ArrayIterator; +use IteratorAggregate; +use Traversable; + +/** + * @template-implements IteratorAggregate + */ +final class Diff implements IteratorAggregate +{ + /** + * @var non-empty-string + */ + private string $from; + + /** + * @var non-empty-string + */ + private string $to; + + /** + * @var list + */ + private array $chunks; + + /** + * @param non-empty-string $from + * @param non-empty-string $to + * @param list $chunks + */ + public function __construct(string $from, string $to, array $chunks = []) + { + $this->from = $from; + $this->to = $to; + $this->chunks = $chunks; + } + + /** + * @return non-empty-string + */ + public function from(): string + { + return $this->from; + } + + /** + * @return non-empty-string + */ + public function to(): string + { + return $this->to; + } + + /** + * @return list + */ + public function chunks(): array + { + return $this->chunks; + } + + /** + * @param list $chunks + */ + public function setChunks(array $chunks): void + { + $this->chunks = $chunks; + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->chunks); + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Differ.php b/trilhas_poo/vendor/sebastian/diff/src/Differ.php new file mode 100644 index 0000000..73e7ec7 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Differ.php @@ -0,0 +1,213 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use const PREG_SPLIT_DELIM_CAPTURE; +use const PREG_SPLIT_NO_EMPTY; +use function array_any; +use function array_unshift; +use function array_values; +use function count; +use function current; +use function end; +use function is_string; +use function key; +use function preg_split; +use function prev; +use function reset; +use function str_ends_with; +use function substr; +use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface; + +final class Differ +{ + public const int OLD = 0; + public const int ADDED = 1; + public const int REMOVED = 2; + public const int DIFF_LINE_END_WARNING = 3; + public const int NO_LINE_END_EOF_WARNING = 4; + private DiffOutputBuilderInterface $outputBuilder; + + public function __construct(DiffOutputBuilderInterface $outputBuilder) + { + $this->outputBuilder = $outputBuilder; + } + + /** + * @param array|string $from + * @param array|string $to + */ + public function diff(array|string $from, array|string $to): string + { + $diff = $this->diffToArray($from, $to); + + return $this->outputBuilder->getDiff($diff); + } + + /** + * @param array|string $from + * @param array|string $to + * + * @return list + */ + public function diffToArray(array|string $from, array|string $to): array + { + if (is_string($from)) { + $from = $this->splitStringByLines($from); + } + + if (is_string($to)) { + $to = $this->splitStringByLines($to); + } + + [$from, $to, $start, $end] = self::getArrayDiffParted($from, $to); + + $diff = []; + + foreach ($start as $token) { + $diff[] = [$token, self::OLD]; + } + + foreach ((new MyersDiff)->calculate(array_values($from), array_values($to)) as $entry) { + $diff[] = $entry; + } + + foreach ($end as $token) { + $diff[] = [$token, self::OLD]; + } + + if ($this->detectUnmatchedLineEndings($diff)) { + array_unshift($diff, ["#Warning: Strings contain different line endings!\n", self::DIFF_LINE_END_WARNING]); + } + + return $diff; + } + + /** + * @return list + */ + private function splitStringByLines(string $input): array + { + $result = preg_split('/(.*\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + + if ($result === false) { + return []; + } + + return $result; + } + + /** + * @param list $diff + */ + private function detectUnmatchedLineEndings(array $diff): bool + { + $newLineBreaks = ['' => true]; + $oldLineBreaks = ['' => true]; + + foreach ($diff as $entry) { + if (self::OLD === $entry[1]) { + /** @phpstan-ignore argument.type */ + $ln = $this->getLinebreak($entry[0]); + $oldLineBreaks[$ln] = true; + $newLineBreaks[$ln] = true; + } elseif (self::ADDED === $entry[1]) { + /** @phpstan-ignore argument.type */ + $newLineBreaks[$this->getLinebreak($entry[0])] = true; + } elseif (self::REMOVED === $entry[1]) { + /** @phpstan-ignore argument.type */ + $oldLineBreaks[$this->getLinebreak($entry[0])] = true; + } + } + + // if either input or output is a single line without breaks than no warning should be raised + if (count($newLineBreaks) === 1 || count($oldLineBreaks) === 1) { + return false; + } + + // two-way compare + if (array_any($newLineBreaks, static fn (bool $set, string $break) => !isset($oldLineBreaks[$break]))) { + return true; + } + + return array_any($oldLineBreaks, static fn (bool $set, string $break) => !isset($newLineBreaks[$break])); + } + + private function getLinebreak(int|string $line): string + { + if (!is_string($line)) { + return ''; + } + + $lc = substr($line, -1); + + if ("\r" === $lc) { + return "\r"; + } + + if ("\n" !== $lc) { + return ''; + } + + if (str_ends_with($line, "\r\n")) { + return "\r\n"; + } + + return "\n"; + } + + /** + * @param array $from + * @param array $to + * + * @return array{0: array, 1: array, 2: array, 3: array} + */ + private static function getArrayDiffParted(array &$from, array &$to): array + { + $start = []; + $end = []; + + reset($to); + + foreach ($from as $k => $v) { + $toK = key($to); + + /** @phpstan-ignore offsetAccess.notFound */ + if ($toK === $k && $v === $to[$k]) { + $start[$k] = $v; + + unset($from[$k], $to[$k]); + } else { + break; + } + } + + end($from); + end($to); + + do { + $fromK = key($from); + $toK = key($to); + + if (null === $fromK || null === $toK || current($from) !== current($to)) { + break; + } + + prev($from); + prev($to); + + /** @phpstan-ignore offsetAccess.notFound */ + $end = [$fromK => $from[$fromK]] + $end; + unset($from[$fromK], $to[$toK]); + } while (true); + + return [$from, $to, $start, $end]; + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Exception/ConfigurationException.php b/trilhas_poo/vendor/sebastian/diff/src/Exception/ConfigurationException.php new file mode 100644 index 0000000..b1c42c8 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Exception/ConfigurationException.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function gettype; +use function is_object; +use function sprintf; +use InvalidArgumentException; + +final class ConfigurationException extends InvalidArgumentException implements Exception +{ + public function __construct(string $option, string $expected, mixed $value, int $code = 0, ?\Exception $previous = null) + { + parent::__construct( + sprintf( + 'Option "%s" must be %s, got "%s".', + $option, + $expected, + /** @phpstan-ignore binaryOp.invalid */ + is_object($value) ? $value::class : (null === $value ? '' : gettype($value) . '#' . $value), + ), + $code, + $previous, + ); + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Exception/Exception.php b/trilhas_poo/vendor/sebastian/diff/src/Exception/Exception.php new file mode 100644 index 0000000..e20d320 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Exception/Exception.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use Throwable; + +interface Exception extends Throwable +{ +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Exception/NoMiddleSnakeFoundException.php b/trilhas_poo/vendor/sebastian/diff/src/Exception/NoMiddleSnakeFoundException.php new file mode 100644 index 0000000..6e9fc02 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Exception/NoMiddleSnakeFoundException.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use LogicException; + +/** + * @codeCoverageIgnore + */ +final class NoMiddleSnakeFoundException extends LogicException implements Exception +{ + public function __construct() + { + parent::__construct('No middle snake found; input invariants violated'); + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Line.php b/trilhas_poo/vendor/sebastian/diff/src/Line.php new file mode 100644 index 0000000..6576bee --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Line.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +final class Line +{ + public const int ADDED = 1; + public const int REMOVED = 2; + public const int UNCHANGED = 3; + private int $type; + private string $content; + + public function __construct(int $type = self::UNCHANGED, string $content = '') + { + $this->type = $type; + $this->content = $content; + } + + public function content(): string + { + return $this->content; + } + + public function type(): int + { + return $this->type; + } + + public function isAdded(): bool + { + return $this->type === self::ADDED; + } + + public function isRemoved(): bool + { + return $this->type === self::REMOVED; + } + + public function isUnchanged(): bool + { + return $this->type === self::UNCHANGED; + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/MyersDiff.php b/trilhas_poo/vendor/sebastian/diff/src/MyersDiff.php new file mode 100644 index 0000000..289f689 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/MyersDiff.php @@ -0,0 +1,250 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use function array_fill; +use function count; +use function intdiv; + +/** + * Linear-space variant of the Myers diff algorithm (Eugene W. Myers, 1986, + * "An O(ND) Difference Algorithm and Its Variations", §4b). + * + * Time: O((N + M) * D) + * Space: O(N + M) + * + * Where N and M are the input lengths and D is the edit distance. + * + * @internal This class is not covered by the backward compatibility promise for PHPUnit + */ +final readonly class MyersDiff +{ + /** + * @param list $from + * @param list $to + * + * @return list edit script as [token, Differ::OLD|ADDED|REMOVED] entries + */ + public function calculate(array $from, array $to): array + { + $diff = []; + + $this->diffRange($from, 0, count($from), $to, 0, count($to), $diff); + + return $this->normalize($diff); + } + + /** + * Within each contiguous run of non-matching entries, emit all REMOVED + * tokens before any ADDED tokens. The Myers algorithm may interleave them + * depending on path tie-breaking; normalizing matches the conventional + * diff(1) output ordering. + * + * @param list $diff + * + * @return list + */ + private function normalize(array $diff): array + { + $result = []; + $i = 0; + $n = count($diff); + + while ($i < $n) { + /** @phpstan-ignore offsetAccess.notFound */ + if ($diff[$i][1] === Differ::OLD) { + $result[] = $diff[$i]; + $i++; + + continue; + } + + $adds = []; + + /** @phpstan-ignore offsetAccess.notFound */ + while ($i < $n && $diff[$i][1] !== Differ::OLD) { + if ($diff[$i][1] === Differ::REMOVED) { + $result[] = $diff[$i]; + } else { + $adds[] = $diff[$i]; + } + + $i++; + } + + foreach ($adds as $entry) { + $result[] = $entry; + } + } + + return $result; + } + + /** + * @param list $a + * @param list $b + * @param list $out + */ + private function diffRange(array $a, int $aLo, int $aHi, array $b, int $bLo, int $bHi, array &$out): void + { + // Trim common prefix. + // $aLo < $aHi <= count($a) and $bLo < $bHi <= count($b) ensure offsets exist. + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + while ($aLo < $aHi && $bLo < $bHi && $a[$aLo] === $b[$bLo]) { + $out[] = [$a[$aLo], Differ::OLD]; + $aLo++; + $bLo++; + } + + // Trim common suffix; defer emission until after the middle is processed. + $suffix = []; + + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + while ($aLo < $aHi && $bLo < $bHi && $a[$aHi - 1] === $b[$bHi - 1]) { + $aHi--; + $bHi--; + + /** @phpstan-ignore offsetAccess.notFound */ + $suffix[] = [$a[$aHi], Differ::OLD]; + } + + $n = $aHi - $aLo; + $m = $bHi - $bLo; + + if ($n === 0) { + for ($j = $bLo; $j < $bHi; $j++) { + /** @phpstan-ignore offsetAccess.notFound */ + $out[] = [$b[$j], Differ::ADDED]; + } + } elseif ($m === 0) { + for ($i = $aLo; $i < $aHi; $i++) { + /** @phpstan-ignore offsetAccess.notFound */ + $out[] = [$a[$i], Differ::REMOVED]; + } + } else { + // Both n > 0 and m > 0 here, so the edit distance is at least 2 + // (one deletion plus one insertion); a single edit would have been + // fully consumed by the prefix/suffix trimming above. + [$xs, $ys, $xe, $ye] = $this->findMiddleSnake($a, $aLo, $aHi, $b, $bLo, $bHi); + + $this->diffRange($a, $aLo, $aLo + $xs, $b, $bLo, $bLo + $ys, $out); + + for ($i = $xs; $i < $xe; $i++) { + /** @phpstan-ignore offsetAccess.notFound */ + $out[] = [$a[$aLo + $i], Differ::OLD]; + } + + $this->diffRange($a, $aLo + $xe, $aHi, $b, $bLo + $ye, $bHi, $out); + } + + // Emit the deferred common suffix in original order. + for ($i = count($suffix) - 1; $i >= 0; $i--) { + /** @phpstan-ignore offsetAccess.notFound */ + $out[] = $suffix[$i]; + } + } + + /** + * Find the middle snake of an optimal D-path through the edit graph using + * bidirectional search. + * + * @param list $a + * @param list $b + * + * @return array{0: int, 1: int, 2: int, 3: int} [xStart, yStart, xEnd, yEnd] in coords relative to (aLo, bLo) + */ + private function findMiddleSnake(array $a, int $aLo, int $aHi, array $b, int $bLo, int $bHi): array + { + // All $vf, $vb offsets below resolve to indices within [0, $size) by the algorithm's + // invariants (|$k| <= $d <= $maxD, $offset = $maxD + 1). The $a, $b accesses are guarded + // by $x < $n, $y < $m bounds and $aHi <= count($a), $bHi <= count($b) by construction. + $n = $aHi - $aLo; + $m = $bHi - $bLo; + $delta = $n - $m; + $deltaIsOdd = ($delta & 1) !== 0; + $maxD = intdiv($n + $m + 1, 2); + $offset = $maxD + 1; + $size = 2 * $maxD + 2; + $vf = array_fill(0, $size, 0); + $vb = array_fill(0, $size, 0); + + for ($d = 0; $d <= $maxD; $d++) { + // Forward pass. + for ($k = -$d; $k <= $d; $k += 2) { + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + if ($k === -$d || ($k !== $d && $vf[$offset + $k - 1] < $vf[$offset + $k + 1])) { + /** @phpstan-ignore offsetAccess.notFound */ + $x = $vf[$offset + $k + 1]; + } else { + /** @phpstan-ignore offsetAccess.notFound */ + $x = $vf[$offset + $k - 1] + 1; + } + + $y = $x - $k; + $xs = $x; + $ys = $y; + + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + while ($x < $n && $y < $m && $a[$aLo + $x] === $b[$bLo + $y]) { + $x++; + $y++; + } + + $vf[$offset + $k] = $x; + + if ($deltaIsOdd) { + $kb = $delta - $k; + + /** @phpstan-ignore offsetAccess.notFound */ + if ($kb >= -($d - 1) && $kb <= $d - 1 && $vf[$offset + $k] + $vb[$offset + $kb] >= $n) { + return [$xs, $ys, $x, $y]; + } + } + } + + // Backward pass. + for ($k = -$d; $k <= $d; $k += 2) { + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + if ($k === -$d || ($k !== $d && $vb[$offset + $k - 1] < $vb[$offset + $k + 1])) { + /** @phpstan-ignore offsetAccess.notFound */ + $x = $vb[$offset + $k + 1]; + } else { + /** @phpstan-ignore offsetAccess.notFound */ + $x = $vb[$offset + $k - 1] + 1; + } + + $y = $x - $k; + $xs = $x; + $ys = $y; + + /** @phpstan-ignore offsetAccess.notFound, offsetAccess.notFound */ + while ($x < $n && $y < $m && $a[$aLo + $n - 1 - $x] === $b[$bLo + $m - 1 - $y]) { + $x++; + $y++; + } + + $vb[$offset + $k] = $x; + + if (!$deltaIsOdd) { + $kf = $delta - $k; + + /** @phpstan-ignore offsetAccess.notFound */ + if ($kf >= -$d && $kf <= $d && $vf[$offset + $kf] + $vb[$offset + $k] >= $n) { + return [$n - $x, $m - $y, $n - $xs, $m - $ys]; + } + } + } + } + + // @codeCoverageIgnoreStart + throw new NoMiddleSnakeFoundException; + // @codeCoverageIgnoreEnd + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php b/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php new file mode 100644 index 0000000..d24a2b3 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function assert; +use function fclose; +use function fopen; +use function fwrite; +use function is_resource; +use function str_ends_with; +use function stream_get_contents; +use function substr; +use SebastianBergmann\Diff\Differ; + +/** + * Builds a diff string representation in a loose unified diff format + * listing only changes lines. Does not include line numbers. + */ +final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface +{ + private string $header; + + public function __construct(string $header = "--- Original\n+++ New\n") + { + $this->header = $header; + } + + /** + * @param list $diff + */ + public function getDiff(array $diff): string + { + $buffer = fopen('php://memory', 'r+b'); + + assert(is_resource($buffer)); + + if ('' !== $this->header) { + fwrite($buffer, $this->header); + + if (!str_ends_with($this->header, "\n")) { + fwrite($buffer, "\n"); + } + } + + foreach ($diff as $diffEntry) { + if ($diffEntry[1] === Differ::ADDED) { + /** @phpstan-ignore binaryOp.invalid */ + fwrite($buffer, '+' . $diffEntry[0]); + } elseif ($diffEntry[1] === Differ::REMOVED) { + /** @phpstan-ignore binaryOp.invalid */ + fwrite($buffer, '-' . $diffEntry[0]); + } elseif ($diffEntry[1] === Differ::DIFF_LINE_END_WARNING) { + /** @phpstan-ignore binaryOp.invalid */ + fwrite($buffer, ' ' . $diffEntry[0]); + + continue; // Warnings should not be tested for line break, it will always be there + } else { /* Not changed (old) 0 */ + continue; // we didn't write the not-changed line, so do not add a line break either + } + + /** @phpstan-ignore argument.type */ + $lc = substr($diffEntry[0], -1); + + if ($lc !== "\n" && $lc !== "\r") { + fwrite($buffer, "\n"); // \No newline at end of file + } + } + + $diff = stream_get_contents($buffer, -1, 0); + fclose($buffer); + + return $diff; + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php b/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php new file mode 100644 index 0000000..a02b74d --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +/** + * Defines how an output builder should take a generated + * diff array and return a string representation of that diff. + */ +interface DiffOutputBuilderInterface +{ + /** + * @param list $diff + */ + public function getDiff(array $diff): string; +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php b/trilhas_poo/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php new file mode 100644 index 0000000..7a4ede8 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php @@ -0,0 +1,414 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff\Output; + +use function array_merge; +use function array_splice; +use function assert; +use function count; +use function fclose; +use function fopen; +use function fwrite; +use function is_bool; +use function is_int; +use function is_resource; +use function is_string; +use function max; +use function min; +use function sprintf; +use function str_ends_with; +use function stream_get_contents; +use function substr; +use SebastianBergmann\Diff\ConfigurationException; +use SebastianBergmann\Diff\Differ; + +/** + * Strict Unified diff output builder. + * + * Generates (strict) Unified diff's (unidiffs) with hunks. + */ +final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface +{ + /** + * @var array{addLineNumbers: bool, collapseRanges: bool, commonLineThreshold: int, contextLines: int, emitDiffLineEndWarning: bool, emitNoLineEndEofWarning: bool, fromFile: null|string, fromFileDate: null|string, header: null|string, toFile: null|string, toFileDate: null|string} + */ + private static array $default = [ + 'addLineNumbers' => true, // when false, hunk header is rendered as `@@ @@` (no line numbers); when true, as `@@ -from,range +to,range @@` + 'collapseRanges' => true, // ranges of length one are rendered with the trailing `,1` + 'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed) + 'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3 + 'emitDiffLineEndWarning' => false, // when true, the `#Warning: Strings contain different line endings!` line inserted by `Differ` is rendered (it is not part of strict unified diff format) + 'emitNoLineEndEofWarning' => true, // when false, the `\ No newline at end of file` marker is suppressed (useful for comparisons not related to files) + 'fromFile' => null, + 'fromFileDate' => null, + 'header' => null, // when provided, used verbatim as the header; otherwise built from `fromFile`/`fromFileDate`/`toFile`/`toFileDate` + 'toFile' => null, + 'toFileDate' => null, + ]; + private bool $addLineNumbers; + private bool $changed; + private bool $collapseRanges; + + /** + * @var positive-int + */ + private int $commonLineThreshold; + private bool $emitDiffLineEndWarning; + private bool $emitNoLineEndEofWarning; + private string $header; + + /** + * @var int<0, max> + */ + private int $contextLines; + + /** + * @param array $options + */ + public function __construct(array $options = []) + { + $options = array_merge(self::$default, $options); + + if (!is_bool($options['addLineNumbers'])) { + throw new ConfigurationException('addLineNumbers', 'a bool', $options['addLineNumbers']); + } + + if (!is_bool($options['collapseRanges'])) { + throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']); + } + + if (!is_int($options['contextLines']) || $options['contextLines'] < 0) { + throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']); + } + + if (!is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] <= 0) { + throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']); + } + + if (!is_bool($options['emitDiffLineEndWarning'])) { + throw new ConfigurationException('emitDiffLineEndWarning', 'a bool', $options['emitDiffLineEndWarning']); + } + + if (!is_bool($options['emitNoLineEndEofWarning'])) { + throw new ConfigurationException('emitNoLineEndEofWarning', 'a bool', $options['emitNoLineEndEofWarning']); + } + + if (null !== $options['header']) { + $this->assertString($options, 'header'); + + /** @phpstan-ignore assign.propertyType */ + $this->header = $options['header']; + } else { + $this->assertString($options, 'fromFile'); + $this->assertString($options, 'toFile'); + $this->assertStringOrNull($options, 'fromFileDate'); + $this->assertStringOrNull($options, 'toFileDate'); + + $this->header = sprintf( + "--- %s%s\n+++ %s%s\n", + /** @phpstan-ignore argument.type */ + $options['fromFile'], + /** @phpstan-ignore binaryOp.invalid */ + null === $options['fromFileDate'] ? '' : "\t" . $options['fromFileDate'], + /** @phpstan-ignore argument.type */ + $options['toFile'], + /** @phpstan-ignore binaryOp.invalid */ + null === $options['toFileDate'] ? '' : "\t" . $options['toFileDate'], + ); + } + + $this->addLineNumbers = $options['addLineNumbers']; + $this->collapseRanges = $options['collapseRanges']; + $this->commonLineThreshold = $options['commonLineThreshold']; + $this->contextLines = $options['contextLines']; + $this->emitDiffLineEndWarning = $options['emitDiffLineEndWarning']; + $this->emitNoLineEndEofWarning = $options['emitNoLineEndEofWarning']; + } + + /** + * @param list $diff + */ + public function getDiff(array $diff): string + { + if (0 === count($diff)) { + return ''; + } + + $this->changed = false; + + $buffer = fopen('php://memory', 'r+b'); + + assert(is_resource($buffer)); + + if ('' !== $this->header) { + fwrite($buffer, $this->header); + + if (!str_ends_with($this->header, "\n")) { + fwrite($buffer, "\n"); + } + } + + $this->writeDiffHunks($buffer, $diff); + + if (!$this->changed) { + fclose($buffer); + + return ''; + } + + $diff = stream_get_contents($buffer, -1, 0); + + fclose($buffer); + + // If the last char is not a linebreak: add it. + // This might happen when both the `from` and `to` do not have a trailing linebreak + $last = substr($diff, -1); + + return "\n" !== $last && "\r" !== $last + ? $diff . "\n" + : $diff; + } + + /** + * @param non-empty-list $diff + */ + private function writeDiffHunks(mixed $output, array $diff): void + { + assert(is_resource($output)); + + // detect "No newline at end of file" and insert into `$diff` if needed + + $upperLimit = count($diff); + + /** @phpstan-ignore offsetAccess.notFound */ + if (0 === $diff[$upperLimit - 1][1]) { + /** @phpstan-ignore argument.type */ + $lc = substr($diff[$upperLimit - 1][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + } else { + // search back for the last `+` and `-` line, + // check if it has a trailing linebreak, else add a warning under it + $toFind = [1 => true, 2 => true]; + + for ($i = $upperLimit - 1; $i >= 0; $i--) { + /** @phpstan-ignore offsetAccess.notFound */ + if (isset($toFind[$diff[$i][1]])) { + unset($toFind[$diff[$i][1]]); + + /** @phpstan-ignore argument.type */ + $lc = substr($diff[$i][0], -1); + + if ("\n" !== $lc) { + array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", Differ::NO_LINE_END_EOF_WARNING]]); + } + + if ($toFind === []) { + break; + } + } + } + } + + // write hunks to output buffer + + $cutOff = max($this->commonLineThreshold, $this->contextLines); + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + $toStart = $fromStart = 1; + + foreach ($diff as $i => $entry) { + if (0 === $entry[1]) { // same + if (false === $hunkCapture) { + $fromStart++; + $toStart++; + + continue; + } + + $sameCount++; + $toRange++; + $fromRange++; + + if ($sameCount === $cutOff) { + $contextStartOffset = ($hunkCapture - $this->contextLines) < 0 + ? $hunkCapture + : $this->contextLines; + + // note: $contextEndOffset = $this->contextLines; + // + // because we never go beyond the end of the diff. + // with the cutoff/contextlines here the follow is never true; + // + // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) { + // $contextEndOffset = count($diff) - 1; + // } + // + // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $cutOff + $this->contextLines + 1, + $fromStart - $contextStartOffset, + $fromRange - $cutOff + $contextStartOffset + $this->contextLines, + $toStart - $contextStartOffset, + $toRange - $cutOff + $contextStartOffset + $this->contextLines, + $output, + ); + + $fromStart += $fromRange; + $toStart += $toRange; + + $hunkCapture = false; + $sameCount = $toRange = $fromRange = 0; + } + + continue; + } + + $sameCount = 0; + + if ($entry[1] === Differ::NO_LINE_END_EOF_WARNING) { + continue; + } + + $this->changed = true; + + if (false === $hunkCapture) { + $hunkCapture = $i; + } + + if (Differ::ADDED === $entry[1]) { // added + $toRange++; + } + + if (Differ::REMOVED === $entry[1]) { // removed + $fromRange++; + } + } + + if (false === $hunkCapture) { + return; + } + + // we end here when cutoff (commonLineThreshold) was not reached, but we were capturing a hunk, + // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold + + $contextStartOffset = $hunkCapture - $this->contextLines < 0 + ? $hunkCapture + : $this->contextLines; + + // prevent trying to write out more common lines than there are in the diff _and_ + // do not write more than configured through the context lines + $contextEndOffset = min($sameCount, $this->contextLines); + + $fromRange -= $sameCount; + $toRange -= $sameCount; + + assert(isset($i) && is_int($i)); + + $this->writeHunk( + $diff, + $hunkCapture - $contextStartOffset, + $i - $sameCount + $contextEndOffset + 1, + $fromStart - $contextStartOffset, + $fromRange + $contextStartOffset + $contextEndOffset, + $toStart - $contextStartOffset, + $toRange + $contextStartOffset + $contextEndOffset, + $output, + ); + } + + /** + * @param list $diff + */ + private function writeHunk( + array $diff, + int $diffStartIndex, + int $diffEndIndex, + int $fromStart, + int $fromRange, + int $toStart, + int $toRange, + mixed $output + ): void { + assert(is_resource($output)); + + if ($this->addLineNumbers) { + fwrite($output, '@@ -' . $fromStart); + + if (!$this->collapseRanges || 1 !== $fromRange) { + fwrite($output, ',' . $fromRange); + } + + fwrite($output, ' +' . $toStart); + + if (!$this->collapseRanges || 1 !== $toRange) { + fwrite($output, ',' . $toRange); + } + + fwrite($output, " @@\n"); + } else { + fwrite($output, "@@ @@\n"); + } + + for ($i = $diffStartIndex; $i < $diffEndIndex; $i++) { + /** @phpstan-ignore offsetAccess.notFound */ + if ($diff[$i][1] === Differ::ADDED) { + $this->changed = true; + + /** @phpstan-ignore binaryOp.invalid */ + fwrite($output, '+' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::REMOVED) { + $this->changed = true; + + /** @phpstan-ignore binaryOp.invalid */ + fwrite($output, '-' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::OLD) { + /** @phpstan-ignore binaryOp.invalid */ + fwrite($output, ' ' . $diff[$i][0]); + } elseif ($diff[$i][1] === Differ::NO_LINE_END_EOF_WARNING) { + /** @phpstan-ignore argument.type */ + fwrite($output, $this->emitNoLineEndEofWarning ? $diff[$i][0] : "\n"); + } elseif ($this->emitDiffLineEndWarning && $diff[$i][1] === Differ::DIFF_LINE_END_WARNING) { + /** @phpstan-ignore binaryOp.invalid */ + fwrite($output, ' ' . $diff[$i][0]); + } + // else: unknown/invalid type or skipped warning - silently skip + } + } + + /** + * @param array $options + */ + private function assertString(array $options, string $option): void + { + $value = $options[$option] ?? null; + + if (!is_string($value)) { + throw new ConfigurationException($option, 'a string', $value); + } + } + + /** + * @param array $options + */ + private function assertStringOrNull(array $options, string $option): void + { + $value = $options[$option] ?? null; + + if (null !== $value && !is_string($value)) { + throw new ConfigurationException($option, 'a string or ', $value); + } + } +} diff --git a/trilhas_poo/vendor/sebastian/diff/src/Parser.php b/trilhas_poo/vendor/sebastian/diff/src/Parser.php new file mode 100644 index 0000000..9b5f9f3 --- /dev/null +++ b/trilhas_poo/vendor/sebastian/diff/src/Parser.php @@ -0,0 +1,126 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace SebastianBergmann\Diff; + +use const PREG_UNMATCHED_AS_NULL; +use function array_pop; +use function count; +use function max; +use function preg_match; +use function preg_split; + +/** + * Unified diff parser. + */ +final class Parser +{ + /** + * @return list + */ + public function parse(string $string): array + { + $lines = preg_split('(\r\n|\r|\n)', $string); + + if ($lines === false) { + return []; + } + + if ($lines !== [] && $lines[count($lines) - 1] === '') { + array_pop($lines); + } + + $lineCount = count($lines); + $diffs = []; + $diff = null; + $collected = []; + + for ($i = 0; $i < $lineCount; $i++) { + if (!isset($lines[$i])) { + continue; + } + + $line = $lines[$i]; + $nextLine = $lines[$i + 1] ?? null; + + if ($nextLine !== null && + preg_match('#^---\h+"?(?P[^\\v\\t"]+)#', $line, $fromMatch) === 1 && + preg_match('#^\\+\\+\\+\\h+"?(?P[^\\v\\t"]+)#', $nextLine, $toMatch) === 1) { + if ($diff !== null) { + $this->parseFileDiff($diff, $collected); + + $diffs[] = $diff; + $collected = []; + } + + $diff = new Diff($fromMatch['file'], $toMatch['file']); + + $i++; + + continue; + } + + if (preg_match('/^(?:diff --git |index [\da-f.]+|[+-]{3} [ab])/', $line) === 1) { + continue; + } + + $collected[] = $line; + } + + if ($diff !== null && $collected !== []) { + $this->parseFileDiff($diff, $collected); + + $diffs[] = $diff; + } + + return $diffs; + } + + /** + * @param string[] $lines + */ + private function parseFileDiff(Diff $diff, array $lines): void + { + $chunks = []; + $chunk = null; + $diffLines = []; + + foreach ($lines as $line) { + if (preg_match('/^@@\s+-(?P\d+)(?:,\s*(?P\d+))?\s+\+(?P\d+)(?:,\s*(?P\d+))?\s+@@/', $line, $match, PREG_UNMATCHED_AS_NULL) === 1) { + $chunk = new Chunk( + (int) $match['start'], + isset($match['startrange']) ? max(0, (int) $match['startrange']) : 1, + (int) $match['end'], + isset($match['endrange']) ? max(0, (int) $match['endrange']) : 1, + ); + + $chunks[] = $chunk; + $diffLines = []; + + continue; + } + + if (preg_match('/^(?P[+ -])?(?P.*)/', $line, $match) === 1) { + $type = Line::UNCHANGED; + + if ($match['type'] === '+') { + $type = Line::ADDED; + } elseif ($match['type'] === '-') { + $type = Line::REMOVED; + } + + $diffLines[] = new Line($type, $match['line']); + + $chunk?->setLines($diffLines); + } + } + + $diff->setChunks($chunks); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Application.php b/trilhas_poo/vendor/symfony/console/Application.php new file mode 100644 index 0000000..72f6862 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Application.php @@ -0,0 +1,1421 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Console\ArgumentResolver\ArgumentResolverInterface; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Command\CompleteCommand; +use Symfony\Component\Console\Command\DumpCompletionCommand; +use Symfony\Component\Console\Command\HelpCommand; +use Symfony\Component\Console\Command\LazyCommand; +use Symfony\Component\Console\Command\ListCommand; +use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\CompletionSuggestions; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Event\ConsoleAlarmEvent; +use Symfony\Component\Console\Event\ConsoleCommandEvent; +use Symfony\Component\Console\Event\ConsoleErrorEvent; +use Symfony\Component\Console\Event\ConsoleSignalEvent; +use Symfony\Component\Console\Event\ConsoleTerminateEvent; +use Symfony\Component\Console\Exception\CommandNotFoundException; +use Symfony\Component\Console\Exception\ExceptionInterface; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Exception\NamespaceNotFoundException; +use Symfony\Component\Console\Exception\RuntimeException; +use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\DebugFormatterHelper; +use Symfony\Component\Console\Helper\DescriptorHelper; +use Symfony\Component\Console\Helper\FormatterHelper; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Helper\ProcessHelper; +use Symfony\Component\Console\Helper\QuestionHelper; +use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputAwareInterface; +use Symfony\Component\Console\Input\InputDefinition; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\ConsoleOutput; +use Symfony\Component\Console\Output\ConsoleOutputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\SignalRegistry\SignalRegistry; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\DependencyInjection\ContainerInterface as SymfonyContainerInterface; +use Symfony\Component\ErrorHandler\ErrorHandler; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; +use Symfony\Contracts\Service\ResetInterface; + +/** + * An Application is the container for a collection of commands. + * + * It is the main entry point of a Console application. + * + * This class is optimized for a standard CLI environment. + * + * Usage: + * + * $app = new Application('myapp', '1.0 (stable)'); + * $app->addCommand(new SimpleCommand()); + * $app->run(); + * + * @author Fabien Potencier + */ +class Application implements ResetInterface +{ + private array $commands = []; + private bool $wantHelps = false; + private ?Command $runningCommand = null; + private ?CommandLoaderInterface $commandLoader = null; + private bool $catchExceptions = true; + private bool $catchErrors = false; + private bool $autoExit = true; + private InputDefinition $definition; + private HelperSet $helperSet; + private ?EventDispatcherInterface $dispatcher = null; + private ?ArgumentResolverInterface $argumentResolver = null; + private Terminal $terminal; + private string $defaultCommand; + private bool $singleCommand = false; + private bool $initialized = false; + private ?SignalRegistry $signalRegistry = null; + private array $signalsToDispatchEvent = []; + private ?int $alarmInterval = null; + + public function __construct( + private string $name = 'UNKNOWN', + private string $version = 'UNKNOWN', + private ?ContainerInterface $container = null, + ) { + $this->terminal = new Terminal(); + $this->defaultCommand = 'list'; + if (\defined('SIGINT') && SignalRegistry::isSupported()) { + $this->signalRegistry = new SignalRegistry(); + $this->signalsToDispatchEvent = [\SIGINT, \SIGQUIT, \SIGTERM, \SIGUSR1, \SIGUSR2, \SIGALRM]; + } + } + + /** + * @final + */ + public function setDispatcher(EventDispatcherInterface $dispatcher): void + { + $this->dispatcher = $dispatcher; + } + + public function getDispatcher(): ?EventDispatcherInterface + { + return $this->dispatcher; + } + + /** + * @final + */ + public function setArgumentResolver(ArgumentResolverInterface $argumentResolver): void + { + $this->argumentResolver = $argumentResolver; + } + + public function getArgumentResolver(): ?ArgumentResolverInterface + { + return $this->argumentResolver; + } + + public function setCommandLoader(CommandLoaderInterface $commandLoader): void + { + $this->commandLoader = $commandLoader; + } + + public function getSignalRegistry(): SignalRegistry + { + if (!$this->signalRegistry) { + throw new RuntimeException('Signals are not supported. Make sure that the "pcntl" extension is installed and that "pcntl_*" functions are not disabled by your php.ini\'s "disable_functions" directive.'); + } + + return $this->signalRegistry; + } + + public function setSignalsToDispatchEvent(int ...$signalsToDispatchEvent): void + { + $this->signalsToDispatchEvent = $signalsToDispatchEvent; + } + + /** + * Sets the interval to schedule a SIGALRM signal in seconds. + */ + public function setAlarmInterval(?int $seconds): void + { + $this->alarmInterval = $seconds; + $this->scheduleAlarm(); + } + + /** + * Gets the interval in seconds on which a SIGALRM signal is dispatched. + */ + public function getAlarmInterval(): ?int + { + return $this->alarmInterval; + } + + private function scheduleAlarm(): void + { + if (null !== $this->alarmInterval) { + $this->getSignalRegistry()->scheduleAlarm($this->alarmInterval); + } + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + * + * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}. + */ + public function run(?InputInterface $input = null, ?OutputInterface $output = null): int + { + if (\function_exists('putenv')) { + @putenv('LINES='.$this->terminal->getHeight()); + @putenv('COLUMNS='.$this->terminal->getWidth()); + } + + $input ??= new ArgvInput(); + $output ??= new ConsoleOutput(); + + $renderException = function (\Throwable $e) use ($output) { + if ($output instanceof ConsoleOutputInterface) { + $this->renderThrowable($e, $output->getErrorOutput()); + } else { + $this->renderThrowable($e, $output); + } + }; + if ($phpHandler = set_exception_handler($renderException)) { + restore_exception_handler(); + if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) { + $errorHandler = true; + } elseif ($errorHandler = $phpHandler[0]->setExceptionHandler($renderException)) { + $phpHandler[0]->setExceptionHandler($errorHandler); + } + } + + $empty = new \stdClass(); + $prevShellVerbosity = [$_ENV['SHELL_VERBOSITY'] ?? $empty, $_SERVER['SHELL_VERBOSITY'] ?? $empty, getenv('SHELL_VERBOSITY')]; + + try { + $this->configureIO($input, $output); + + $exitCode = $this->doRun($input, $output); + } catch (\Throwable $e) { + if ($e instanceof \Exception && !$this->catchExceptions) { + throw $e; + } + if (!$e instanceof \Exception && !$this->catchErrors) { + throw $e; + } + + $renderException($e); + + $exitCode = $e->getCode(); + if (is_numeric($exitCode)) { + $exitCode = (int) $exitCode; + if ($exitCode <= 0) { + $exitCode = 1; + } + } else { + $exitCode = 1; + } + } finally { + // if the exception handler changed, keep it + // otherwise, unregister $renderException + if (!$phpHandler) { + if (set_exception_handler($renderException) === $renderException) { + restore_exception_handler(); + } + restore_exception_handler(); + } elseif (!$errorHandler) { + $finalHandler = $phpHandler[0]->setExceptionHandler(null); + if ($finalHandler !== $renderException) { + $phpHandler[0]->setExceptionHandler($finalHandler); + } + } + + // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it + // to its previous value to avoid one command verbosity to spread to other commands + if ($empty === $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity[0]) { + unset($_ENV['SHELL_VERBOSITY']); + } + if ($empty === $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity[1]) { + unset($_SERVER['SHELL_VERBOSITY']); + } + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY'.(false === ($prevShellVerbosity[2] ?? false) ? '' : '='.$prevShellVerbosity[2])); + } + } + + if ($this->autoExit) { + if ($exitCode > 255) { + $exitCode = 255; + } + + exit($exitCode); + } + + return $exitCode; + } + + /** + * Runs the current application. + * + * @return int 0 if everything went fine, or an error code + */ + public function doRun(InputInterface $input, OutputInterface $output): int + { + if (true === $input->hasParameterOption(['--version', '-V'], true)) { + $output->writeln($this->getLongVersion()); + + return 0; + } + + try { + // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument. + $input->bind($this->getDefinition()); + } catch (ExceptionInterface) { + // Errors must be ignored, full binding/validation happens later when the command is known. + } + + $name = $this->getCommandName($input); + if (true === $input->hasParameterOption(['--help', '-h'], true)) { + if (!$name) { + $name = 'help'; + $input = new ArrayInput(['command_name' => $this->defaultCommand]); + } else { + $this->wantHelps = true; + } + } + + if (!$name) { + $name = $this->defaultCommand; + $definition = $this->getDefinition(); + $definition->setArguments(array_merge( + $definition->getArguments(), + [ + 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name), + ] + )); + } + + try { + $this->runningCommand = null; + // the command name MUST be the first element of the input + $command = $this->find($name); + } catch (\Throwable $e) { + if (($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException) && 1 === \count($alternatives = $e->getAlternatives()) && $input->isInteractive()) { + $alternative = $alternatives[0]; + + $style = new SymfonyStyle($input, $output); + $output->writeln(''); + $formattedBlock = (new FormatterHelper())->formatBlock(\sprintf('Command "%s" is not defined.', $name), 'error', true); + $output->writeln($formattedBlock); + if (!$style->confirm(\sprintf('Do you want to run "%s" instead? ', $alternative), false)) { + if (null !== $this->dispatcher) { + $event = new ConsoleErrorEvent($input, $output, $e); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + + return $event->getExitCode(); + } + + return 1; + } + + $command = $this->find($alternative); + } else { + if (null !== $this->dispatcher) { + $event = new ConsoleErrorEvent($input, $output, $e); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + + if (0 === $event->getExitCode()) { + return 0; + } + + $e = $event->getError(); + } + + try { + if ($e instanceof CommandNotFoundException && $namespace = $this->findNamespace($name)) { + $helper = new DescriptorHelper(); + $helper->describe($output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output, $this, [ + 'format' => 'txt', + 'raw_text' => false, + 'namespace' => $namespace, + 'short' => false, + ]); + + return isset($event) ? $event->getExitCode() : 1; + } + + throw $e; + } catch (NamespaceNotFoundException) { + throw $e; + } + } + } + + if ($command instanceof LazyCommand) { + $command = $command->getCommand(); + } + + $this->runningCommand = $command; + $exitCode = $this->doRunCommand($command, $input, $output); + $this->runningCommand = null; + + return $exitCode; + } + + public function reset(): void + { + if ($this->container?->has('services_resetter')) { + $this->container->get('services_resetter')->reset(); + } + } + + public function setHelperSet(HelperSet $helperSet): void + { + $this->helperSet = $helperSet; + } + + /** + * Get the helper set associated with the command. + */ + public function getHelperSet(): HelperSet + { + return $this->helperSet ??= $this->getDefaultHelperSet(); + } + + public function setDefinition(InputDefinition $definition): void + { + $this->definition = $definition; + } + + /** + * Gets the InputDefinition related to this Application. + */ + public function getDefinition(): InputDefinition + { + $this->definition ??= $this->getDefaultInputDefinition(); + + if ($this->singleCommand) { + $this->definition->setArguments(); + } + + return $this->definition; + } + + /** + * Adds suggestions to $suggestions for the current completion input (e.g. option or argument). + */ + public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void + { + if ( + CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() + && 'command' === $input->getCompletionName() + ) { + foreach ($this->all() as $name => $command) { + // skip hidden commands and aliased commands as they already get added below + if ($command->isHidden() || $command->getName() !== $name) { + continue; + } + $suggestions->suggestValue(new Suggestion($command->getName(), $command->getDescription())); + foreach ($command->getAliases() as $name) { + $suggestions->suggestValue(new Suggestion($name, $command->getDescription())); + } + } + + return; + } + + if (CompletionInput::TYPE_OPTION_NAME === $input->getCompletionType()) { + $suggestions->suggestOptions($this->getDefinition()->getOptions()); + } + + if ( + CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType() + && ($definition = $this->getDefinition())->hasOption($input->getCompletionName()) + ) { + $definition->getOption($input->getCompletionName())->complete($input, $suggestions); + + return; + } + } + + /** + * Gets the help message. + */ + public function getHelp(): string + { + return $this->getLongVersion(); + } + + /** + * Gets whether to catch exceptions or not during commands execution. + */ + public function areExceptionsCaught(): bool + { + return $this->catchExceptions; + } + + /** + * Sets whether to catch exceptions or not during commands execution. + */ + public function setCatchExceptions(bool $boolean): void + { + $this->catchExceptions = $boolean; + } + + /** + * Sets whether to catch errors or not during commands execution. + */ + public function setCatchErrors(bool $catchErrors = true): void + { + $this->catchErrors = $catchErrors; + } + + /** + * Gets whether to automatically exit after a command execution or not. + */ + public function isAutoExitEnabled(): bool + { + return $this->autoExit; + } + + /** + * Sets whether to automatically exit after a command execution or not. + */ + public function setAutoExit(bool $boolean): void + { + $this->autoExit = $boolean; + } + + /** + * Gets the name of the application. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Sets the application name. + */ + public function setName(string $name): void + { + $this->name = $name; + } + + /** + * Gets the application version. + */ + public function getVersion(): string + { + return $this->version; + } + + /** + * Sets the application version. + */ + public function setVersion(string $version): void + { + $this->version = $version; + } + + /** + * Returns the long version of the application. + */ + public function getLongVersion(): string + { + if ('UNKNOWN' !== $this->getName()) { + if ('UNKNOWN' !== $this->getVersion()) { + $version = \sprintf('%s %s', $this->getName(), $this->getVersion()); + } else { + $version = $this->getName(); + } + } else { + $version = 'Console Tool'; + } + + if ($this->container instanceof SymfonyContainerInterface && $this->container->hasParameter('kernel.environment')) { + $version .= \sprintf(' (env: %s, debug: %s)', $this->container->getParameter('kernel.environment'), $this->container->getParameter('kernel.debug') ? 'true' : 'false'); + } + + return $version; + } + + /** + * Registers a new command. + */ + public function register(string $name): Command + { + return $this->addCommand(new Command($name)); + } + + /** + * Adds an array of command objects. + * + * If a Command is not enabled it will not be added. + * + * @param callable[]|Command[] $commands An array of commands + */ + public function addCommands(array $commands): void + { + foreach ($commands as $command) { + $this->addCommand($command); + } + } + + /** + * Adds a command object. + * + * If a command with the same name already exists, it will be overridden. + * If the command is not enabled it will not be added. + */ + public function addCommand(callable|Command $command): ?Command + { + $this->init(); + + if (!$command instanceof Command) { + $command = new Command(null, $command); + } + + $command->setApplication($this); + + if (!$command->isEnabled()) { + $command->setApplication(null); + + return null; + } + + if (!$command instanceof LazyCommand) { + // Will throw if the command is not correctly initialized. + $command->getDefinition(); + } + + if (!$command->getName()) { + throw new LogicException(\sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command))); + } + + $this->commands[$command->getName()] = $command; + + foreach ($command->getAliases() as $alias) { + $this->commands[$alias] = $command; + } + + return $command; + } + + /** + * Returns a registered command by name or alias. + * + * @throws CommandNotFoundException When given command name does not exist + */ + public function get(string $name): Command + { + $this->init(); + + if (!$this->has($name)) { + throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name)); + } + + // When the command has a different name than the one used at the command loader level + if (!isset($this->commands[$name])) { + throw new CommandNotFoundException(\sprintf('The "%s" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".', $name)); + } + + $command = $this->commands[$name]; + + if ($this->wantHelps) { + $this->wantHelps = false; + + $helpCommand = $this->get('help'); + $helpCommand->setCommand($command); + + return $helpCommand; + } + + return $command; + } + + /** + * Returns true if the command exists, false otherwise. + */ + public function has(string $name): bool + { + $this->init(); + + return isset($this->commands[$name]) || ($this->commandLoader?->has($name) && $this->addCommand($this->commandLoader->get($name))); + } + + /** + * Returns an array of all unique namespaces used by currently registered commands. + * + * It does not return the global namespace which always exists. + * + * @return string[] + */ + public function getNamespaces(): array + { + $namespaces = []; + foreach ($this->all() as $command) { + if ($command->isHidden()) { + continue; + } + + $namespaces[] = $this->extractAllNamespaces($command->getName()); + + foreach ($command->getAliases() as $alias) { + $namespaces[] = $this->extractAllNamespaces($alias); + } + } + + return array_values(array_unique(array_filter(array_merge([], ...$namespaces)))); + } + + /** + * Finds a registered namespace by a name or an abbreviation. + * + * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous + */ + public function findNamespace(string $namespace): string + { + $allNamespaces = $this->getNamespaces(); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*'; + $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces); + + if (!$namespaces) { + $message = \sprintf('There are no commands defined in the "%s" namespace.', $namespace); + + if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) { + if (1 == \count($alternatives)) { + $message .= "\n\nDid you mean this?\n "; + } else { + $message .= "\n\nDid you mean one of these?\n "; + } + + $message .= implode("\n ", $alternatives); + } + + throw new NamespaceNotFoundException($message, $alternatives); + } + + $exact = \in_array($namespace, $namespaces, true); + if (\count($namespaces) > 1 && !$exact) { + sort($namespaces); + + throw new NamespaceNotFoundException(\sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces)); + } + + return $exact ? $namespace : reset($namespaces); + } + + /** + * Finds a command by name or alias. + * + * Contrary to get, this command tries to find the best + * match if you give it an abbreviation of a name or alias. + * + * @throws CommandNotFoundException When command name is incorrect or ambiguous + */ + public function find(string $name): Command + { + $this->init(); + + $aliases = []; + + foreach ($this->commands as $command) { + foreach ($command->getAliases() as $alias) { + if (!$this->has($alias)) { + $this->commands[$alias] = $command; + } + } + } + + if ($this->has($name)) { + return $this->get($name); + } + + $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands); + $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*'; + $commands = preg_grep('{^'.$expr.'}', $allCommands); + + if (!$commands) { + $commands = preg_grep('{^'.$expr.'}i', $allCommands); + } + + sort($commands); + + // if no commands matched or we just matched namespaces + if (!$commands || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) { + if (false !== $pos = strrpos($name, ':')) { + // check if a namespace exists and contains commands + $this->findNamespace(substr($name, 0, $pos)); + } + + $message = \sprintf('Command "%s" is not defined.', $name); + + if ($alternatives = $this->findAlternatives($name, $allCommands)) { + $wantHelps = $this->wantHelps; + $this->wantHelps = false; + + // remove hidden commands + if ($alternatives = array_filter($alternatives, fn ($name) => !$this->get($name)->isHidden())) { + $message .= \sprintf("\n\nDid you mean %s?\n %s", 1 === \count($alternatives) ? 'this' : 'one of these', implode("\n ", $alternatives)); + } + $this->wantHelps = $wantHelps; + } + + throw new CommandNotFoundException($message, array_values($alternatives)); + } + + // filter out aliases for commands which are already on the list + if (\count($commands) > 1) { + $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands; + $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) { + if (!$commandList[$nameOrAlias] instanceof Command) { + $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias); + } + + $commandName = $commandList[$nameOrAlias]->getName(); + + $aliases[$nameOrAlias] = $commandName; + + return $commandName === $nameOrAlias || !\in_array($commandName, $commands, true); + })); + } + + // check whether all commands left are aliases to the same one + if (\count($commands) > 1) { + $uniqueCommands = array_unique(array_map(function ($nameOrAlias) use (&$commandList) { + if (!$commandList[$nameOrAlias] instanceof Command) { + $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias); + } + + return $commandList[$nameOrAlias]->getName(); + }, $commands)); + + if (1 === \count($uniqueCommands)) { + $commands = [reset($uniqueCommands)]; + } + } + + if (\count($commands) > 1) { + sort($commands); + $usableWidth = $this->terminal->getWidth() - 10; + $abbrevs = array_values($commands); + $maxLen = 0; + foreach ($abbrevs as $abbrev) { + $maxLen = max(Helper::width($abbrev), $maxLen); + } + $abbrevs = array_map(static function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) { + if ($commandList[$cmd]->isHidden()) { + unset($commands[array_search($cmd, $commands)]); + + return false; + } + + $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); + + return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; + }, array_values($commands)); + + if (\count($commands) > 1) { + $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs)); + + throw new CommandNotFoundException(\sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $name, $suggestions), array_values($commands)); + } + } + + $command = $commands ? $this->get(reset($commands)) : null; + + if (!$command || $command->isHidden()) { + throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name)); + } + + return $command; + } + + /** + * Gets the commands (registered in the given namespace if provided). + * + * The array keys are the full names and the values the command instances. + * + * @return Command[] + */ + public function all(?string $namespace = null): array + { + $this->init(); + + if (null === $namespace) { + if (!$this->commandLoader) { + return $this->commands; + } + + $commands = $this->commands; + foreach ($this->commandLoader->getNames() as $name) { + if (!isset($commands[$name]) && $this->has($name)) { + $commands[$name] = $this->get($name); + } + } + + return $commands; + } + + $commands = []; + foreach ($this->commands as $name => $command) { + if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) { + $commands[$name] = $command; + } + } + + if ($this->commandLoader) { + foreach ($this->commandLoader->getNames() as $name) { + if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) { + $commands[$name] = $this->get($name); + } + } + } + + return $commands; + } + + /** + * Returns an array of possible abbreviations given a set of names. + * + * @return string[][] + */ + public static function getAbbreviations(array $names): array + { + $abbrevs = []; + foreach ($names as $name) { + for ($len = \strlen($name); $len > 0; --$len) { + $abbrev = substr($name, 0, $len); + $abbrevs[$abbrev][] = $name; + } + } + + return $abbrevs; + } + + public function renderThrowable(\Throwable $e, OutputInterface $output): void + { + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + + $this->doRenderThrowable($e, $output); + + if (null !== $this->runningCommand) { + $output->writeln(\sprintf('%s', OutputFormatter::escape(\sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET); + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + } + } + + protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void + { + do { + $message = trim($e->getMessage()); + if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $class = get_debug_type($e); + $title = \sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''); + $len = Helper::width($title); + } else { + $len = 0; + } + + if (str_contains($message, "@anonymous\0")) { + $message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)?[0-9a-fA-F]++/', static fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $message); + } + + $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX; + $lines = []; + foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) { + foreach ($this->splitStringByWidth($line, $width - 4) as $line) { + // pre-format lines to get the right string length + $lineLength = Helper::width($line) + 4; + $lines[] = [$line, $lineLength]; + + $len = max($lineLength, $len); + } + } + + $messages = []; + if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $messages[] = \sprintf('%s', OutputFormatter::escape(\sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a'))); + } + $messages[] = $emptyLine = \sprintf('%s', str_repeat(' ', $len)); + if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $messages[] = \sprintf('%s%s', $title, str_repeat(' ', max(0, $len - Helper::width($title)))); + } + foreach ($lines as $line) { + $messages[] = \sprintf(' %s %s', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1])); + } + $messages[] = $emptyLine; + $messages[] = ''; + + $output->writeln($messages, OutputInterface::VERBOSITY_QUIET); + + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { + $output->writeln('Exception trace:', OutputInterface::VERBOSITY_QUIET); + + // exception related properties + $trace = $e->getTrace(); + + array_unshift($trace, [ + 'function' => '', + 'file' => $e->getFile() ?: 'n/a', + 'line' => $e->getLine() ?: 'n/a', + 'args' => [], + ]); + + for ($i = 0, $count = \count($trace); $i < $count; ++$i) { + $class = $trace[$i]['class'] ?? ''; + $type = $trace[$i]['type'] ?? ''; + $function = $trace[$i]['function'] ?? ''; + $file = $trace[$i]['file'] ?? 'n/a'; + $line = $trace[$i]['line'] ?? 'n/a'; + + $output->writeln(\sprintf(' %s%s at %s:%s', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET); + } + + $output->writeln('', OutputInterface::VERBOSITY_QUIET); + } + } while ($e = $e->getPrevious()); + } + + /** + * Configures the input and output instances based on the user arguments and options. + */ + protected function configureIO(InputInterface $input, OutputInterface $output): void + { + if ($input->hasParameterOption(['--ansi'], true)) { + $output->setDecorated(true); + } elseif ($input->hasParameterOption(['--no-ansi'], true)) { + $output->setDecorated(false); + } + + $shellVerbosity = match (true) { + $input->hasParameterOption(['--silent'], true) => -2, + $input->hasParameterOption(['--quiet', '-q'], true) => -1, + $input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true) => 3, + $input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true) => 2, + $input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true) => 1, + default => (int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'] ?? getenv('SHELL_VERBOSITY')), + }; + + $output->setVerbosity(match ($shellVerbosity) { + -2 => OutputInterface::VERBOSITY_SILENT, + -1 => OutputInterface::VERBOSITY_QUIET, + 1 => OutputInterface::VERBOSITY_VERBOSE, + 2 => OutputInterface::VERBOSITY_VERY_VERBOSE, + 3 => OutputInterface::VERBOSITY_DEBUG, + default => ($shellVerbosity = 0) ?: $output->getVerbosity(), + }); + + if (0 > $shellVerbosity || $input->hasParameterOption(['--no-interaction', '-n'], true)) { + $input->setInteractive(false); + } + + if (\function_exists('putenv')) { + @putenv('SHELL_VERBOSITY='.$shellVerbosity); + } + $_ENV['SHELL_VERBOSITY'] = $shellVerbosity; + $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity; + } + + /** + * Runs the current command. + * + * If an event dispatcher has been attached to the application, + * events are also dispatched during the life-cycle of the command. + * + * @return int 0 if everything went fine, or an error code + */ + protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int + { + foreach ($command->getHelperSet() as $helper) { + if ($helper instanceof InputAwareInterface) { + $helper->setInput($input); + } + } + + $registeredSignals = false; + if (($commandSignals = $command->getSubscribedSignals()) || $this->dispatcher && $this->signalsToDispatchEvent) { + $signalRegistry = $this->getSignalRegistry(); + + $registeredSignals = true; + $this->getSignalRegistry()->pushCurrentHandlers(); + + if ($this->dispatcher) { + // We register application signals, so that we can dispatch the event + foreach ($this->signalsToDispatchEvent as $signal) { + $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal); + $alarmEvent = \SIGALRM === $signal ? new ConsoleAlarmEvent($command, $input, $output) : null; + + $signalRegistry->register($signal, function ($signal) use ($signalEvent, $alarmEvent, $command, $commandSignals, $input, $output) { + $this->dispatcher->dispatch($signalEvent, ConsoleEvents::SIGNAL); + $exitCode = $signalEvent->getExitCode(); + + if (null !== $alarmEvent) { + if (false !== $exitCode) { + $alarmEvent->setExitCode($exitCode); + } else { + $alarmEvent->abortExit(); + } + $this->dispatcher->dispatch($alarmEvent); + $exitCode = $alarmEvent->getExitCode(); + } + + // If the command is signalable, we call the handleSignal() method + if (\in_array($signal, $commandSignals, true)) { + $exitCode = $command->handleSignal($signal, $exitCode); + } + + if (\SIGALRM === $signal) { + $this->scheduleAlarm(); + } + + if (false !== $exitCode) { + $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode, $signal); + $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE); + + exit($event->getExitCode()); + } + }); + } + + // then we register command signals, but not if already handled after the dispatcher + $commandSignals = array_diff($commandSignals, $this->signalsToDispatchEvent); + } + + foreach ($commandSignals as $signal) { + $signalRegistry->register($signal, function (int $signal) use ($command): void { + if (\SIGALRM === $signal) { + $this->scheduleAlarm(); + } + + if (false !== $exitCode = $command->handleSignal($signal)) { + exit($exitCode); + } + }); + } + } + + if (null === $this->dispatcher) { + try { + return $command->run($input, $output); + } finally { + if ($registeredSignals) { + $this->getSignalRegistry()->popPreviousHandlers(); + } + } + } + + // bind before the console.command event, so the listeners have access to input options/arguments + try { + $command->mergeApplicationDefinition(); + $input->bind($command->getDefinition()); + } catch (ExceptionInterface) { + // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition + } + + $event = new ConsoleCommandEvent($command, $input, $output); + $e = null; + + try { + $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND); + + if ($event->commandShouldRun()) { + $exitCode = $command->run($input, $output); + } else { + $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED; + } + } catch (\Throwable $e) { + $event = new ConsoleErrorEvent($input, $output, $e, $command); + $this->dispatcher->dispatch($event, ConsoleEvents::ERROR); + $e = $event->getError(); + + if (0 === $exitCode = $event->getExitCode()) { + $e = null; + } + } finally { + if ($registeredSignals) { + $this->getSignalRegistry()->popPreviousHandlers(); + } + } + + $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode); + $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE); + + if (null !== $e) { + throw $e; + } + + return $event->getExitCode(); + } + + /** + * Gets the name of the command based on input. + */ + protected function getCommandName(InputInterface $input): ?string + { + return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument(); + } + + /** + * Gets the default input definition. + */ + protected function getDefaultInputDefinition(): InputDefinition + { + return new InputDefinition([ + new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), + new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display help for the given command. When no command is given display help for the '.$this->defaultCommand.' command'), + new InputOption('--silent', null, InputOption::VALUE_NONE, 'Do not output any message'), + new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Only errors are displayed. All other output is suppressed'), + new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'), + new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'), + new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null), + new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'), + ]); + } + + /** + * Gets the default commands that should always be available. + * + * @return Command[] + */ + protected function getDefaultCommands(): array + { + return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()]; + } + + /** + * Gets the default helper set with the helpers that should always be available. + */ + protected function getDefaultHelperSet(): HelperSet + { + return new HelperSet([ + new FormatterHelper(), + new DebugFormatterHelper(), + new ProcessHelper(), + new QuestionHelper(), + ]); + } + + /** + * Returns abbreviated suggestions in string format. + */ + private function getAbbreviationSuggestions(array $abbrevs): string + { + return ' '.implode("\n ", $abbrevs); + } + + /** + * Returns the namespace part of the command name. + * + * This method is not part of public API and should not be used directly. + */ + public function extractNamespace(string $name, ?int $limit = null): string + { + $parts = explode(':', $name, -1); + + return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit)); + } + + /** + * Finds alternative of $name among $collection, + * if nothing is found in $collection, try in $abbrevs. + * + * @return string[] + */ + private function findAlternatives(string $name, iterable $collection): array + { + $threshold = 1e3; + $alternatives = []; + + $collectionParts = []; + foreach ($collection as $item) { + $collectionParts[$item] = explode(':', $item); + } + + foreach (explode(':', $name) as $i => $subname) { + foreach ($collectionParts as $collectionName => $parts) { + $exists = isset($alternatives[$collectionName]); + if (!isset($parts[$i]) && $exists) { + $alternatives[$collectionName] += $threshold; + continue; + } elseif (!isset($parts[$i])) { + continue; + } + + $lev = levenshtein($subname, $parts[$i]); + if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) { + $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev; + } elseif ($exists) { + $alternatives[$collectionName] += $threshold; + } + } + } + + foreach ($collection as $item) { + $lev = levenshtein($name, $item); + if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) { + $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev; + } + } + + $alternatives = array_filter($alternatives, static fn ($lev) => $lev < 2 * $threshold); + ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); + + return array_keys($alternatives); + } + + /** + * Sets the default Command name. + * + * @return $this + */ + public function setDefaultCommand(string $commandName, bool $isSingleCommand = false): static + { + $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0]; + + if ($isSingleCommand) { + // Ensure the command exist + $this->find($commandName); + + $this->singleCommand = true; + } + + return $this; + } + + /** + * @internal + */ + public function isSingleCommand(): bool + { + return $this->singleCommand; + } + + private function splitStringByWidth(string $string, int $width): array + { + // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. + // additionally, array_slice() is not enough as some character has doubled width. + // we need a function to split string not by character count but by string width + if (false === $encoding = mb_detect_encoding($string, null, true)) { + return str_split($string, $width); + } + + $utf8String = mb_convert_encoding($string, 'utf8', $encoding); + $lines = []; + $line = ''; + + $offset = 0; + while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) { + $offset += \strlen($m[0]); + + foreach (preg_split('//u', $m[0]) as $char) { + // test if $char could be appended to current line + if (Helper::width($line.$char) <= $width) { + $line .= $char; + continue; + } + // if not, push current line to array and make new line + $lines[] = str_pad($line, $width); + $line = $char; + } + } + + $lines[] = \count($lines) ? str_pad($line, $width) : $line; + + return mb_convert_encoding($lines, $encoding, 'utf8'); + } + + /** + * Returns all namespaces of the command name. + * + * @return string[] + */ + private function extractAllNamespaces(string $name): array + { + // -1 as third argument is needed to skip the command short name when exploding + $parts = explode(':', $name, -1); + $namespaces = []; + + foreach ($parts as $part) { + if (\count($namespaces)) { + $namespaces[] = end($namespaces).':'.$part; + } else { + $namespaces[] = $part; + } + } + + return $namespaces; + } + + private function init(): void + { + if ($this->initialized) { + return; + } + $this->initialized = true; + + foreach ($this->getDefaultCommands() as $command) { + $this->addCommand($command); + } + + $this->registerContainerServices(); + } + + private function registerContainerServices(): void + { + if (!$this->container) { + return; + } + + if ($this->container->has('event_dispatcher')) { + $this->setDispatcher($this->container->get('event_dispatcher')); + } + if ($this->container->has('console.argument_resolver')) { + $this->setArgumentResolver($this->container->get('console.argument_resolver')); + } + if ($this->container->has('console.command_loader')) { + $this->setCommandLoader($this->container->get('console.command_loader')); + } + + if (!$commandIds = match (true) { + !$this->container instanceof SymfonyContainerInterface => $this->container->has('console.command.ids') ? $this->container->get('console.command.ids') : [], + $this->container->hasParameter('console.command.ids') => $this->container->getParameter('console.command.ids'), + default => [], + }) { + return; + } + + $lazyCommandIds = match (true) { + !$this->container instanceof SymfonyContainerInterface => $this->container->has('console.lazy_command.ids') ? $this->container->get('console.lazy_command.ids') : [], + $this->container->hasParameter('console.lazy_command.ids') => $this->container->getParameter('console.lazy_command.ids'), + default => [], + }; + + foreach ($commandIds as $id) { + if (!isset($lazyCommandIds[$id])) { + $this->addCommand($this->container->get($id)); + } + } + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolver.php new file mode 100644 index 0000000..3aac1e1 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolver.php @@ -0,0 +1,163 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Console\ArgumentResolver\Exception\NearMissValueResolverException; +use Symfony\Component\Console\ArgumentResolver\Exception\ResolverNotFoundException; +use Symfony\Component\Console\ArgumentResolver\ValueResolver as Resolver; +use Symfony\Component\Console\ArgumentResolver\ValueResolver\ValueResolverInterface; +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Attribute\ValueResolver; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Cursor; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\RawInputInterface; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Contracts\Service\ServiceProviderInterface; + +/** + * Resolves the arguments passed to a console command. + * + * @author Robin Chalas + */ +final class ArgumentResolver implements ArgumentResolverInterface +{ + /** + * @param iterable $argumentValueResolvers + */ + public function __construct( + private iterable $argumentValueResolvers = [], + private ?ContainerInterface $namedResolvers = null, + ) { + } + + public function getArguments(InputInterface $input, callable $command, ?\ReflectionFunctionAbstract $reflector = null): array + { + $reflector ??= new \ReflectionFunction($command(...)); + + $argumentReflectors = []; + foreach ($reflector->getParameters() as $param) { + $argumentReflectors[$param->getName()] = new ReflectionMember($param); + } + + $arguments = []; + + foreach ($argumentReflectors as $argumentName => $member) { + $argumentValueResolvers = $this->argumentValueResolvers; + $disabledResolvers = []; + + if ($this->namedResolvers && $attributes = $member->getAttributes(ValueResolver::class)) { + $resolverName = null; + foreach ($attributes as $attribute) { + if ($attribute->disabled) { + $disabledResolvers[$attribute->resolver] = true; + } elseif ($resolverName) { + throw new \LogicException(\sprintf('You can only pin one resolver per argument, but argument "$%s" of "%s()" has more.', $member->getName(), $member->getSourceName())); + } else { + $resolverName = $attribute->resolver; + } + } + + if ($resolverName) { + if (!$this->namedResolvers->has($resolverName)) { + throw new ResolverNotFoundException($resolverName, $this->namedResolvers instanceof ServiceProviderInterface ? array_keys($this->namedResolvers->getProvidedServices()) : []); + } + + $argumentValueResolvers = [ + $this->namedResolvers->get($resolverName), + ]; + } + } + + $valueResolverExceptions = []; + foreach ($argumentValueResolvers as $name => $resolver) { + if (isset($disabledResolvers[\is_int($name) ? $resolver::class : $name])) { + continue; + } + + try { + $count = 0; + foreach ($resolver->resolve($argumentName, $input, $member) as $argument) { + ++$count; + $arguments[] = $argument; + } + } catch (NearMissValueResolverException $e) { + $valueResolverExceptions[] = $e; + } + + if (1 < $count && !$member->isVariadic()) { + throw new \InvalidArgumentException(\sprintf('"%s::resolve()" must yield at most one value for non-variadic arguments.', get_debug_type($resolver))); + } + + if ($count) { + continue 2; + } + } + + // For variadic parameters with explicit input mapping, 0 values is valid + if ($member->isVariadic() && (Argument::tryFrom($member->getMember()) || Option::tryFrom($member->getMember()))) { + continue; + } + + $type = $member->getType(); + $typeName = $type instanceof \ReflectionNamedType ? $type->getName() : null; + + if ($typeName && \in_array($typeName, [ + InputInterface::class, + RawInputInterface::class, + OutputInterface::class, + SymfonyStyle::class, + Cursor::class, + \Symfony\Component\Console\Application::class, + Command::class, + ], true)) { + continue; + } + + $reasons = array_map(static fn (NearMissValueResolverException $e) => $e->getMessage(), $valueResolverExceptions); + if (!$reasons) { + $reasons[] = \sprintf('The parameter has no #[Argument], #[Option], or #[MapInput] attribute, and its type "%s" cannot be auto-resolved.', $typeName ?? 'unknown'); + $reasons[] = 'Add an attribute to map this parameter to command input.'; + } + + throw new \RuntimeException(\sprintf('Could not resolve parameter "$%s" of command "%s".'."\n\n".'Possible reasons:'."\n".' • '.implode("\n • ", $reasons), $member->getName(), $member->getSourceName())); + } + + return $arguments; + } + + /** + * @return iterable + */ + public static function getDefaultArgumentValueResolvers(): iterable + { + $builtinTypeResolver = new Resolver\BuiltinTypeValueResolver(); + $backedEnumResolver = new Resolver\BackedEnumValueResolver(); + $dateTimeResolver = new Resolver\DateTimeValueResolver(); + $inputFileResolver = new Resolver\InputFileValueResolver(); + + return [ + $backedEnumResolver, + new Resolver\UidValueResolver(), + $inputFileResolver, + $builtinTypeResolver, + new Resolver\MapInputValueResolver($builtinTypeResolver, $backedEnumResolver, $dateTimeResolver), + $dateTimeResolver, + new Resolver\DefaultValueResolver(), + new Resolver\VariadicValueResolver(), + ]; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolverInterface.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolverInterface.php new file mode 100644 index 0000000..b734aba --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ArgumentResolverInterface.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver; + +use Symfony\Component\Console\ArgumentResolver\Exception\ResolverNotFoundException; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Determines the arguments for a specific Console Command. + * + * @author Robin Chalas + * @author Fabien Potencier + * @author Nicolas Grekas + */ +interface ArgumentResolverInterface +{ + /** + * Returns the arguments to pass to the Console Command after resolution. + * + * @throws \RuntimeException When no value could be provided for a required argument + * @throws ResolverNotFoundException + */ + public function getArguments(InputInterface $input, callable $command, ?\ReflectionFunctionAbstract $reflector = null): array; +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/NearMissValueResolverException.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/NearMissValueResolverException.php new file mode 100644 index 0000000..34a22e3 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/NearMissValueResolverException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\Exception; + +/** + * Lets value resolvers tell when an argument could be under their watch but failed to be resolved. + * + * Throwing this exception inside `ValueResolverInterface::resolve` does not interrupt the value resolvers chain. + */ +final class NearMissValueResolverException extends \RuntimeException +{ +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/ResolverNotFoundException.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/ResolverNotFoundException.php new file mode 100644 index 0000000..3e3797a --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/Exception/ResolverNotFoundException.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\Exception; + +final class ResolverNotFoundException extends \RuntimeException +{ + /** + * @param string[] $alternatives + */ + public function __construct(string $name, array $alternatives = []) + { + $msg = \sprintf('You have requested a non-existent resolver "%s".', $name); + if ($alternatives) { + if (1 === \count($alternatives)) { + $msg .= ' Did you mean this: "'; + } else { + $msg .= ' Did you mean one of these: "'; + } + $msg .= implode('", "', $alternatives).'"?'; + } + + parent::__construct($msg); + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/TraceableArgumentResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/TraceableArgumentResolver.php new file mode 100644 index 0000000..a966ae1 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/TraceableArgumentResolver.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver; + +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Robin Chalas + */ +class TraceableArgumentResolver implements ArgumentResolverInterface +{ + public function __construct( + private ArgumentResolverInterface $resolver, + private Stopwatch $stopwatch, + ) { + } + + public function getArguments(InputInterface $input, callable $command, ?\ReflectionFunctionAbstract $reflector = null): array + { + $e = $this->stopwatch->start('command.get_arguments'); + + try { + return $this->resolver->getArguments($input, $command, $reflector); + } finally { + $e->stop(); + } + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BackedEnumValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BackedEnumValueResolver.php new file mode 100644 index 0000000..7e29cf2 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BackedEnumValueResolver.php @@ -0,0 +1,90 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\InvalidOptionException; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Resolves a BackedEnum instance from a Command argument or option. + * + * @author Robin Chalas + * @author Jérôme Tamarelle + * @author Maxime Steinhausser + */ +final class BackedEnumValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if ($argument = Argument::tryFrom($member->getMember())) { + if (!is_subclass_of($argument->typeName, \BackedEnum::class)) { + return []; + } + + return [$this->resolveArgument($argument, $input)]; + } + + if ($option = Option::tryFrom($member->getMember())) { + if (!is_subclass_of($option->typeName, \BackedEnum::class)) { + return []; + } + + return [$this->resolveOption($option, $input)]; + } + + return []; + } + + private function resolveArgument(Argument $argument, InputInterface $input): ?\BackedEnum + { + $value = $input->getArgument($argument->name); + + if (null === $value) { + return null; + } + + if ($value instanceof $argument->typeName) { + return $value; + } + + if (!\is_string($value) && !\is_int($value)) { + throw InvalidArgumentException::fromEnumValue($argument->name, get_debug_type($value), $argument->suggestedValues); + } + + return $argument->typeName::tryFrom($value) + ?? throw InvalidArgumentException::fromEnumValue($argument->name, $value, $argument->suggestedValues); + } + + private function resolveOption(Option $option, InputInterface $input): ?\BackedEnum + { + $value = $input->getOption($option->name); + + if (null === $value) { + return null; + } + + if ($value instanceof $option->typeName) { + return $value; + } + + if (!\is_string($value) && !\is_int($value)) { + throw InvalidOptionException::fromEnumValue($option->name, get_debug_type($value), $option->suggestedValues); + } + + return $option->typeName::tryFrom($value) + ?? throw InvalidOptionException::fromEnumValue($option->name, $value, $option->suggestedValues); + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BuiltinTypeValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BuiltinTypeValueResolver.php new file mode 100644 index 0000000..e6015df --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/BuiltinTypeValueResolver.php @@ -0,0 +1,75 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Resolves values from #[Argument] or #[Option] attributes for built-in PHP types. + * + * Handles: string, bool, int, float, array + * + * @author Robin Chalas + */ +final class BuiltinTypeValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if ($member->isVariadic()) { + return []; + } + + if ($argument = Argument::tryFrom($member->getMember())) { + if (is_subclass_of($argument->typeName, \BackedEnum::class)) { + return []; + } + + return [$input->getArgument($argument->name)]; + } + + if ($option = Option::tryFrom($member->getMember())) { + if (is_subclass_of($option->typeName, \BackedEnum::class)) { + return []; + } + + return [$this->resolveOption($option, $input)]; + } + + return []; + } + + private function resolveOption(Option $option, InputInterface $input): mixed + { + $value = $input->getOption($option->name); + + if (null === $value && \in_array($option->typeName, Option::ALLOWED_UNION_TYPES, true)) { + return true; + } + + if ('array' === $option->typeName && $option->allowNull && [] === $value) { + return null; + } + + if ('bool' === $option->typeName) { + if ($option->allowNull && null === $value) { + return null; + } + + return $value ?? $option->default; + } + + return $value; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DateTimeValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DateTimeValueResolver.php new file mode 100644 index 0000000..828f7b7 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DateTimeValueResolver.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Psr\Clock\ClockInterface; +use Symfony\Component\Console\Attribute\MapDateTime; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Resolves a \DateTime* instance as a command input argument or option. + * + * @author Benjamin Eberlei + * @author Tim Goudriaan + * @author Robin Chalas + */ +final class DateTimeValueResolver implements ValueResolverInterface +{ + public function __construct( + private readonly ?ClockInterface $clock = null, + ) { + } + + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + $type = $member->getType(); + + if (!$type instanceof \ReflectionNamedType || !is_a($type->getName(), \DateTimeInterface::class, true)) { + return []; + } + + $attribute = $member->getAttribute(MapDateTime::class); + + $inputName = $attribute?->argument ?? $attribute?->option ?? $member->getInputName(); + + // Try to get value from argument or option + $value = null; + if ($input->hasArgument($inputName)) { + $value = $input->getArgument($inputName); + } elseif ($input->hasOption($inputName)) { + $value = $input->getOption($inputName); + } + + /** @var class-string<\DateTimeImmutable>|class-string<\DateTime> $class */ + $class = \DateTimeInterface::class === $type->getName() ? \DateTimeImmutable::class : $type->getName(); + + if (!$value) { + if ($member->isNullable()) { + return [null]; + } + if (!$this->clock) { + return [new $class()]; + } + $value = $this->clock->now(); + } + + if ($value instanceof \DateTimeInterface) { + return [$value instanceof $class ? $value : $class::createFromInterface($value)]; + } + + $format = $attribute?->format; + + if (null !== $format) { + $date = $class::createFromFormat($format, $value, $this->clock?->now()->getTimeZone()); + + if (($class::getLastErrors() ?: ['warning_count' => 0])['warning_count']) { + $date = false; + } + } else { + if (false !== filter_var($value, \FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]])) { + $value = '@'.$value; + } + try { + $date = new $class($value, $this->clock?->now()->getTimeZone()); + } catch (\Exception) { + $date = false; + } + } + + if (!$date) { + $message = \sprintf('Invalid date given for parameter "$%s".', $argumentName); + if ($format) { + $message .= \sprintf(' Expected format: "%s".', $format); + } + $message .= ' Use #[MapDateTime(format: \'your-format\')] to specify a custom format.'; + + throw new \RuntimeException($message); + } + + return [$date]; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DefaultValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DefaultValueResolver.php new file mode 100644 index 0000000..ac8f0aa --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/DefaultValueResolver.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Yields the default value defined in the command signature when no input value has been explicitly passed. + * + * @author Iltar van der Berg + * @author Robin Chalas + */ +final class DefaultValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if ($member->hasDefaultValue()) { + return [$member->getDefaultValue()]; + } + + if ($member->isNullable() && !$member->isVariadic()) { + return [null]; + } + + return []; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/InputFileValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/InputFileValueResolver.php new file mode 100644 index 0000000..176abed --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/InputFileValueResolver.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\File\InputFile; +use Symfony\Component\Console\Input\InputInterface; + +/** + * @author Robin Chalas + */ +final class InputFileValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + $type = $member->getType(); + + if (!$type instanceof \ReflectionNamedType || InputFile::class !== $type->getName()) { + return []; + } + + if ($argument = Argument::tryFrom($member->getMember())) { + return $this->resolveValue($input->getArgument($argument->name), $member); + } + + if ($option = Option::tryFrom($member->getMember())) { + return $this->resolveValue($input->getOption($option->name), $member); + } + + return []; + } + + private function resolveValue(mixed $value, ReflectionMember $member): iterable + { + if (!$value) { + if ($member->isNullable()) { + return [null]; + } + + return []; + } + + if ($value instanceof InputFile) { + return [$value]; + } + + return [InputFile::fromPath($value)]; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/MapInputValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/MapInputValueResolver.php new file mode 100644 index 0000000..1fa68b1 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/MapInputValueResolver.php @@ -0,0 +1,128 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\MapInput; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\InputValidationFailedException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Validator\Validator\ValidatorInterface; + +/** + * Resolves the value of a input argument/option to an object holding the #[MapInput] attribute. + * + * @author Yonel Ceruto + * @author Robin Chalas + */ +final class MapInputValueResolver implements ValueResolverInterface +{ + public function __construct( + private readonly ValueResolverInterface $builtinTypeResolver, + private readonly ValueResolverInterface $backedEnumResolver, + private readonly ValueResolverInterface $dateTimeResolver, + private readonly ?ValidatorInterface $validator = null, + ) { + } + + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if (!$attribute = MapInput::tryFrom($member->getMember())) { + return []; + } + + $instance = $this->resolveMapInput($attribute, $input); + $violations = $this->validator?->validate($instance, null, $attribute->validationGroups) ?? []; + + if (!\count($violations)) { + return [$instance]; + } + + $map = $this->buildPropertyToInputMap($attribute); + $messages = []; + foreach ($violations as $violation) { + $path = $violation->getPropertyPath(); + $label = $map[$path] ?? $path; + $messages[] = $label.': '.$violation->getMessage(); + } + + throw new InputValidationFailedException(implode("\n", $messages), $violations); + } + + private function resolveMapInput(MapInput $mapInput, InputInterface $input): object + { + $instance = $mapInput->getClass()->newInstanceWithoutConstructor(); + + foreach ($mapInput->getDefinition() as $name => $spec) { + // ignore required arguments that are not set yet (may happen in interactive mode) + if ($spec instanceof Argument && $spec->isRequired() && \in_array($input->getArgument($spec->name), [null, []], true)) { + continue; + } + + $instance->$name = match (true) { + $spec instanceof Argument => $this->resolveArgumentSpec($spec, $mapInput->getClass()->getProperty($name), $input), + $spec instanceof Option => $this->resolveOptionSpec($spec, $mapInput->getClass()->getProperty($name), $input), + $spec instanceof MapInput => $this->resolveMapInput($spec, $input), + }; + } + + return $instance; + } + + /** + * @return array + */ + private function buildPropertyToInputMap(MapInput $mapInput, string $prefix = ''): array + { + $map = []; + foreach ($mapInput->getDefinition() as $propertyName => $spec) { + $path = $prefix.$propertyName; + $map[$path] = match (true) { + $spec instanceof Argument => $spec->name, + $spec instanceof Option => '--'.$spec->name, + default => $path, + }; + if ($spec instanceof MapInput) { + $map += $this->buildPropertyToInputMap($spec, $path.'.'); + } + } + + return $map; + } + + private function resolveArgumentSpec(Argument $argument, \ReflectionProperty $property, InputInterface $input): mixed + { + if (is_subclass_of($argument->typeName, \BackedEnum::class)) { + return iterator_to_array($this->backedEnumResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } + + if (is_a($argument->typeName, \DateTimeInterface::class, true)) { + return iterator_to_array($this->dateTimeResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } + + return iterator_to_array($this->builtinTypeResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } + + private function resolveOptionSpec(Option $option, \ReflectionProperty $property, InputInterface $input): mixed + { + if (is_subclass_of($option->typeName, \BackedEnum::class)) { + return iterator_to_array($this->backedEnumResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } + + if (is_a($option->typeName, \DateTimeInterface::class, true)) { + return iterator_to_array($this->dateTimeResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } + + return iterator_to_array($this->builtinTypeResolver->resolve($property->name, $input, new ReflectionMember($property)))[0] ?? null; + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ServiceValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ServiceValueResolver.php new file mode 100644 index 0000000..1eeccb6 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ServiceValueResolver.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Console\ArgumentResolver\Exception\NearMissValueResolverException; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; + +/** + * Yields a service from a service locator keyed by command and argument name. + * + * @author Nicolas Grekas + * @author Robin Chalas + */ +final class ServiceValueResolver implements ValueResolverInterface +{ + public function __construct( + private readonly ContainerInterface $container, + ) { + } + + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + $command = $input->getFirstArgument(); + + if ($command && $this->container->has($command)) { + $locator = $this->container->get($command); + if ($locator instanceof ContainerInterface && $locator->has($argumentName)) { + try { + return [$locator->get($argumentName)]; + } catch (RuntimeException|\Throwable $e) { + $what = \sprintf('argument $%s', $argumentName); + $message = str_replace(\sprintf('service "%s"', $argumentName), $what, $e->getMessage()); + $what .= \sprintf(' of command "%s"', $command); + $message = preg_replace('/service "\.service_locator\.[^"]++"/', $what, $message); + + if ($e->getMessage() === $message) { + $message = \sprintf('Cannot resolve %s: %s', $what, $message); + } + + throw new NearMissValueResolverException($message, $e->getCode(), $e); + } + } + } + + $type = $member->getType(); + + if (!$type instanceof \ReflectionNamedType || $type->isBuiltin()) { + return []; + } + + $typeName = $type->getName(); + + if (!$this->container->has($typeName)) { + return []; + } + + try { + $service = $this->container->get($typeName); + + if (!$service instanceof $typeName) { + throw new NearMissValueResolverException(\sprintf('Service "%s" exists in the container but is not an instance of "%s".', $typeName, $typeName)); + } + + return [$service]; + } catch (\Throwable $e) { + throw new NearMissValueResolverException(\sprintf('Cannot resolve parameter "$%s" of type "%s": %s', $argumentName, $typeName, $e->getMessage()), previous: $e); + } + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/TraceableValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/TraceableValueResolver.php new file mode 100644 index 0000000..cf13351 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/TraceableValueResolver.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Robin Chalas + */ +final class TraceableValueResolver implements ValueResolverInterface +{ + public function __construct( + private ValueResolverInterface $inner, + private Stopwatch $stopwatch, + ) { + } + + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + $method = $this->inner::class.'::'.__FUNCTION__; + $this->stopwatch->start($method, 'command.argument_value_resolver'); + + try { + yield from $this->inner->resolve($argumentName, $input, $member); + } finally { + $this->stopwatch->stop($method); + } + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/UidValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/UidValueResolver.php new file mode 100644 index 0000000..a2bf61c --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/UidValueResolver.php @@ -0,0 +1,87 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\InvalidOptionException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Uid\AbstractUid; + +/** + * Resolves an AbstractUid instance from a Command argument or option. + * + * @author Robin Chalas + */ +final class UidValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if ($argument = Argument::tryFrom($member->getMember())) { + if (!is_subclass_of($argument->typeName, AbstractUid::class)) { + return []; + } + + return [$this->resolveArgument($argument, $input)]; + } + + if ($option = Option::tryFrom($member->getMember())) { + if (!is_subclass_of($option->typeName, AbstractUid::class)) { + return []; + } + + return [$this->resolveOption($option, $input)]; + } + + return []; + } + + private function resolveArgument(Argument $argument, InputInterface $input): ?AbstractUid + { + $value = $input->getArgument($argument->name); + + if (null === $value) { + return null; + } + + if ($value instanceof $argument->typeName) { + return $value; + } + + if (!\is_string($value) || !$argument->typeName::isValid($value)) { + throw new InvalidArgumentException(\sprintf('The uid for the "%s" argument is invalid.', $argument->name)); + } + + return $argument->typeName::fromString($value); + } + + private function resolveOption(Option $option, InputInterface $input): ?AbstractUid + { + $value = $input->getOption($option->name); + + if (null === $value) { + return null; + } + + if ($value instanceof $option->typeName) { + return $value; + } + + if (!\is_string($value) || !$option->typeName::isValid($value)) { + throw new InvalidOptionException(\sprintf('The uid for the "--%s" option is invalid.', $option->name)); + } + + return $option->typeName::fromString($value); + } +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ValueResolverInterface.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ValueResolverInterface.php new file mode 100644 index 0000000..09e9d08 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/ValueResolverInterface.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Responsible for resolving the value of a Command argument based on its + * parameter metadata and the Command MapInput. + * + * @author Nicolas Grekas + * @author Robin Chalas + */ +interface ValueResolverInterface +{ + /** + * Returns the possible value(s) for the argument. + */ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable; +} diff --git a/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/VariadicValueResolver.php b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/VariadicValueResolver.php new file mode 100644 index 0000000..f90916b --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/ArgumentResolver/ValueResolver/VariadicValueResolver.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\ArgumentResolver\ValueResolver; + +use Symfony\Component\Console\Attribute\Argument; +use Symfony\Component\Console\Attribute\Option; +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Input\InputInterface; + +/** + * Yields a variadic argument's values from the input. + * + * @author Robin Chalas + */ +final class VariadicValueResolver implements ValueResolverInterface +{ + public function resolve(string $argumentName, InputInterface $input, ReflectionMember $member): iterable + { + if (!$member->isVariadic()) { + return []; + } + + if ($argument = Argument::tryFrom($member->getMember())) { + $values = $input->getArgument($argument->name); + + if (!\is_array($values)) { + throw new \InvalidArgumentException(\sprintf('The action argument "...$%1$s" is required to be an array, the input argument "%1$s" contains a type of "%2$s" instead.', $argument->name, get_debug_type($values))); + } + + return $values; + } + + if ($option = Option::tryFrom($member->getMember())) { + $values = $input->getOption($option->name); + + if (!\is_array($values)) { + throw new \InvalidArgumentException(\sprintf('The action argument "...$%1$s" is required to be an array, the input option "--%1$s" contains a type of "%2$s" instead.', $option->name, get_debug_type($values))); + } + + return $values; + } + + return []; + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/Argument.php b/trilhas_poo/vendor/symfony/console/Attribute/Argument.php new file mode 100644 index 0000000..815d7db --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/Argument.php @@ -0,0 +1,127 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Completion\CompletionInput; +use Symfony\Component\Console\Completion\Suggestion; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\String\UnicodeString; + +#[\Attribute(\Attribute::TARGET_PARAMETER | \Attribute::TARGET_PROPERTY)] +class Argument +{ + public mixed $default = null; + public array|\Closure $suggestedValues; + + /** + * @internal + * + * @var string|class-string<\BackedEnum> + */ + public string $typeName = ''; + private ?int $mode = null; + private ?InteractiveAttributeInterface $interactiveAttribute = null; + + /** + * Represents a console command definition. + * + * If unset, the `name` value will be inferred from the parameter definition. + * + * @param array|callable(CompletionInput):list $suggestedValues The values used for input completion + */ + public function __construct( + public string $description = '', + public string $name = '', + array|callable $suggestedValues = [], + ) { + $this->suggestedValues = \is_callable($suggestedValues) ? $suggestedValues(...) : $suggestedValues; + } + + /** + * @internal + */ + public static function tryFrom(\ReflectionParameter|\ReflectionProperty $member): ?self + { + $reflection = new ReflectionMember($member); + + if (!$self = $reflection->getAttribute(self::class)) { + return null; + } + + $type = $reflection->getType(); + $name = $reflection->getName(); + + if (!$type instanceof \ReflectionNamedType) { + throw new LogicException(\sprintf('The %s "$%s" of "%s" must have a named type. Untyped, Union or Intersection types are not supported for command arguments.', $reflection->getMemberName(), $name, $reflection->getSourceName())); + } + + $self->typeName = $type->getName(); + + if (!$self->name) { + $self->name = (new UnicodeString($name))->kebab(); + } + + $self->default = $reflection->hasDefaultValue() ? $reflection->getDefaultValue() : null; + + $isOptional = $reflection->hasDefaultValue() || $reflection->isNullable() || $reflection->isVariadic(); + $self->mode = $isOptional ? InputArgument::OPTIONAL : InputArgument::REQUIRED; + if ('array' === $self->typeName || $reflection->isVariadic()) { + $self->mode |= InputArgument::IS_ARRAY; + } + + if (\is_array($self->suggestedValues) && !\is_callable($self->suggestedValues) && 2 === \count($self->suggestedValues) && ($instance = $reflection->getSourceThis()) && $instance::class === $self->suggestedValues[0] && \is_callable([$instance, $self->suggestedValues[1]])) { + // In case that the callback is declared as a static method `[Foo::class, 'methodName']` - yet it is not callable, + // while non-static method `[Foo $instance, 'methodName']` would be callable, we transform the callback on the fly into a non-static version. + $self->suggestedValues = [$instance, $self->suggestedValues[1]]; + } + + if (is_subclass_of($self->typeName, \BackedEnum::class) && !$self->suggestedValues) { + $self->suggestedValues = array_column($self->typeName::cases(), 'value'); + } + + $self->interactiveAttribute = Ask::tryFrom($member, $self->name) ?? AskChoice::tryFrom($member, $self->name); + + if ($self->interactiveAttribute && $isOptional) { + throw new LogicException(\sprintf('The %s "$%s" argument of "%s" cannot be both interactive and optional.', $reflection->getMemberName(), $self->name, $reflection->getSourceName())); + } + + return $self; + } + + /** + * @internal + */ + public function toInputArgument(): InputArgument + { + $suggestedValues = \is_callable($this->suggestedValues) ? ($this->suggestedValues)(...) : $this->suggestedValues; + + return new InputArgument($this->name, $this->mode, $this->description, $this->default, $suggestedValues); + } + + /** + * @internal + */ + public function getInteractiveAttribute(): ?InteractiveAttributeInterface + { + return $this->interactiveAttribute; + } + + /** + * @internal + */ + public function isRequired(): bool + { + return InputArgument::REQUIRED === (InputArgument::REQUIRED & $this->mode); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/AsCommand.php b/trilhas_poo/vendor/symfony/console/Attribute/AsCommand.php new file mode 100644 index 0000000..a6a4ca8 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/AsCommand.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * Service tag to autoconfigure commands. + */ +#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD)] +final class AsCommand +{ + /** + * @param string $name The name of the command, used when calling it (i.e. "cache:clear") + * @param string|null $description The description of the command, displayed with the help page + * @param string[] $aliases The list of aliases of the command. The command will be executed when using one of them (i.e. "cache:clean") + * @param bool $hidden If true, the command won't be shown when listing all the available commands, but it can still be run as any other command + * @param string|null $help The help content of the command, displayed with the help page + * @param string[] $usages The list of usage examples, displayed with the help page + */ + public function __construct( + public string $name, + public ?string $description = null, + array $aliases = [], + bool $hidden = false, + public ?string $help = null, + public array $usages = [], + ) { + if (!$hidden && !$aliases) { + return; + } + + $name = explode('|', $name); + $name = array_merge($name, $aliases); + + if ($hidden && '' !== $name[0]) { + array_unshift($name, ''); + } + + $this->name = implode('|', $name); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/AsTargetedValueResolver.php b/trilhas_poo/vendor/symfony/console/Attribute/AsTargetedValueResolver.php new file mode 100644 index 0000000..813f707 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/AsTargetedValueResolver.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * Service tag to autoconfigure targeted value resolvers. + */ +#[\Attribute(\Attribute::TARGET_CLASS)] +class AsTargetedValueResolver +{ + /** + * @param string|null $name The name with which the resolver can be targeted + */ + public function __construct(public readonly ?string $name = null) + { + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/Ask.php b/trilhas_poo/vendor/symfony/console/Attribute/Ask.php new file mode 100644 index 0000000..722f417 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/Ask.php @@ -0,0 +1,173 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\InvalidArgumentException; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Input\File\InputFile; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; +use Symfony\Component\Console\Question\FileQuestion; +use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Validator\Constraint; + +#[\Attribute(\Attribute::TARGET_PARAMETER | \Attribute::TARGET_PROPERTY)] +class Ask implements InteractiveAttributeInterface +{ + public ?\Closure $normalizer; + public ?\Closure $validator; + private \Closure $closure; + + /** + * @param string $question The question to ask the user + * @param string|bool|int|float|null $default The default answer to return if the user enters nothing + * @param bool $hidden Whether the user response must be hidden or not + * @param bool $multiline Whether the user response should accept newline characters + * @param bool $trimmable Whether the user response must be trimmed or not + * @param int|null $timeout The maximum time the user has to answer the question in seconds + * @param callable|null $validator The validator for the question + * @param int|null $maxAttempts The maximum number of attempts allowed to answer the question. + * Null means an unlimited number of attempts + */ + public function __construct( + public string $question, + public string|bool|int|float|null $default = null, + public bool $hidden = false, + public bool $multiline = false, + public bool $trimmable = true, + public ?int $timeout = null, + ?callable $normalizer = null, + ?callable $validator = null, + public ?int $maxAttempts = null, + /** @var Constraint[] */ + public array $constraints = [], + ) { + $this->normalizer = $normalizer ? $normalizer(...) : null; + $this->validator = $validator ? $validator(...) : null; + } + + /** + * @internal + */ + public static function tryFrom(\ReflectionParameter|\ReflectionProperty $member, string $name): ?self + { + $reflection = new ReflectionMember($member); + + if (!$self = $reflection->getAttribute(self::class)) { + return null; + } + + $type = $reflection->getType(); + + if (!$type instanceof \ReflectionNamedType) { + throw new LogicException(\sprintf('The %s "$%s" of "%s" must have a named type. Untyped, Union or Intersection types are not supported for interactive questions.', $reflection->getMemberName(), $name, $reflection->getSourceName())); + } + + $self->closure = function (SymfonyStyle $io, InputInterface $input) use ($self, $reflection, $name, $type) { + if ($reflection->isProperty() && isset($this->{$reflection->getName()})) { + return; + } + + if ($reflection->isParameter() && !\in_array($input->getArgument($name), [null, []], true)) { + return; + } + + $typeName = $type->getName(); + + if (InputFile::class === $typeName) { + $question = new FileQuestion($self->question); + $question->setValidator($self->validator); + $question->setMaxAttempts($self->maxAttempts); + $question->setConstraints($self->constraints); + $value = $io->askQuestion($question); + + if (null === $value && !$reflection->isNullable()) { + return; + } + + if ($reflection->isProperty()) { + $this->{$reflection->getName()} = $value; + } else { + $input->setArgument($name, $value); + } + + return; + } + + if ('bool' === $typeName) { + $self->default ??= false; + + if (!\is_bool($self->default)) { + throw new LogicException(\sprintf('The "%s::$default" value for the %s "$%s" of "%s" must be a boolean.', self::class, $reflection->getMemberName(), $name, $reflection->getSourceName())); + } + + $question = new ConfirmationQuestion($self->question, $self->default); + } else { + $question = new Question($self->question, $self->default); + } + $question->setHidden($self->hidden); + $question->setMultiline($self->multiline); + $question->setTrimmable($self->trimmable); + $question->setTimeout($self->timeout); + + if (!$self->validator && $reflection->isProperty() && 'array' !== $typeName) { + $self->validator = fn (mixed $value): mixed => $this->{$reflection->getName()} = $value; + } + + $question->setValidator($self->validator); + $question->setMaxAttempts($self->maxAttempts); + $question->setConstraints($self->constraints); + + if ($self->normalizer) { + $question->setNormalizer($self->normalizer); + } elseif (is_subclass_of($typeName, \BackedEnum::class)) { + /** @var class-string<\BackedEnum> $backedType */ + $backedType = $reflection->getType()->getName(); + $question->setNormalizer(static fn (string|int $value) => $backedType::tryFrom($value) ?? throw InvalidArgumentException::fromEnumValue($reflection->getName(), $value, array_column($backedType::cases(), 'value'))); + } + + if ('array' === $typeName) { + $value = []; + while ($v = $io->askQuestion($question)) { + if ("\x4" === $v || \PHP_EOL === $v || ($question->isTrimmable() && '' === $v = trim($v))) { + break; + } + $value[] = $v; + } + } else { + $value = $io->askQuestion($question); + } + + if (null === $value && !$reflection->isNullable()) { + return; + } + + if ($reflection->isProperty()) { + $this->{$reflection->getName()} = $value; + } else { + $input->setArgument($name, $value); + } + }; + + return $self; + } + + /** + * @internal + */ + public function getFunction(object $instance): \ReflectionFunction + { + return new \ReflectionFunction($this->closure->bindTo($instance, $instance::class)); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/AskChoice.php b/trilhas_poo/vendor/symfony/console/Attribute/AskChoice.php new file mode 100644 index 0000000..0283899 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/AskChoice.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Question\ChoiceQuestion; +use Symfony\Component\Console\Style\SymfonyStyle; + +#[\Attribute(\Attribute::TARGET_PARAMETER | \Attribute::TARGET_PROPERTY)] +class AskChoice implements InteractiveAttributeInterface +{ + public ?\Closure $validator; + public array|\Closure $choices; + private \Closure $closure; + + /** + * @param string $question The question to ask the user + * @param array|callable():array $choices The list of available choices (leave empty to use enum cases) + * @param string|int|float|null $default The default answer to return if the user enters nothing + * @param string $errorMessage The error message when the answer is invalid + * @param string $prompt The prompt displayed before the user input + * @param callable|null $validator The validator for the answer + * @param int|null $maxAttempts The maximum number of attempts allowed to answer the question. + * Null means an unlimited number of attempts + */ + public function __construct( + public string $question, + array|callable $choices = [], + public string|int|float|null $default = null, + public string $errorMessage = 'Value "%s" is invalid', + public string $prompt = ' > ', + ?callable $validator = null, + public ?int $maxAttempts = null, + ) { + $this->validator = $validator ? $validator(...) : null; + $this->choices = \is_callable($choices) ? $choices(...) : $choices; + } + + /** + * @internal + */ + public static function tryFrom(\ReflectionParameter|\ReflectionProperty $member, string $name): ?self + { + $reflection = new ReflectionMember($member); + + if (!$self = $reflection->getAttribute(self::class)) { + return null; + } + + $type = $reflection->getType(); + + if (!$type instanceof \ReflectionNamedType) { + throw new LogicException(\sprintf('The %s "$%s" of "%s" must have a named type. Untyped, Union or Intersection types are not supported for choice questions.', $reflection->getMemberName(), $name, $reflection->getSourceName())); + } + + $isBackedEnum = is_subclass_of($type->getName(), \BackedEnum::class); + + // Validate that choices are provided or can be derived from enum + if (!$self->choices && !$isBackedEnum) { + throw new LogicException(\sprintf('The #[AskChoice] attribute for the %s "$%s" of "%s" requires either explicit choices or a BackedEnum type.', $reflection->getMemberName(), $name, $reflection->getSourceName())); + } + + $self->closure = function (SymfonyStyle $io, InputInterface $input) use ($self, $reflection, $name, $type, $isBackedEnum) { + if ($reflection->isProperty() && isset($this->{$reflection->getName()})) { + return; + } + + if ($reflection->isParameter() && !\in_array($input->getArgument($name), [null, []], true)) { + return; + } + + $choices = $self->choices instanceof \Closure ? ($self->choices)() : $self->choices; + + // Derive choices from enum cases if not provided + if (!$choices && $isBackedEnum) { + /** @var class-string<\BackedEnum> $enumClass */ + $enumClass = $type->getName(); + $choices = array_column($enumClass::cases(), 'value'); + } + + $question = new ChoiceQuestion($self->question, $choices, $self->default); + $question->setMultiselect('array' === $type->getName()); + $question->setErrorMessage($self->errorMessage); + $question->setPrompt($self->prompt); + $question->setMaxAttempts($self->maxAttempts); + + if (!$self->validator && $reflection->isProperty() && !$isBackedEnum && 'array' !== $type->getName()) { + $self->validator = fn (mixed $value): mixed => $this->{$reflection->getName()} = $value; + } + + if ($self->validator) { + $question->setValidator($self->validator); + } + + $value = $io->askQuestion($question); + + if (null === $value && !$reflection->isNullable()) { + return; + } + + // Convert back to enum if needed + if ($isBackedEnum) { + /** @var class-string<\BackedEnum> $enumClass */ + $enumClass = $type->getName(); + if ($question->isMultiselect() && \is_array($value)) { + $value = array_map(static fn ($v) => $enumClass::from($v), $value); + } else { + $value = $enumClass::from($value); + } + } + + if ($reflection->isProperty()) { + $this->{$reflection->getName()} = $value; + } else { + $input->setArgument($name, $value); + } + }; + + return $self; + } + + /** + * @internal + */ + public function getFunction(object $instance): \ReflectionFunction + { + return new \ReflectionFunction($this->closure->bindTo($instance, $instance::class)); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/Interact.php b/trilhas_poo/vendor/symfony/console/Attribute/Interact.php new file mode 100644 index 0000000..b1d4544 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/Interact.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +use Symfony\Component\Console\Exception\LogicException; + +#[\Attribute(\Attribute::TARGET_METHOD)] +class Interact implements InteractiveAttributeInterface +{ + private \ReflectionMethod $method; + + /** + * @internal + */ + public static function tryFrom(\ReflectionMethod $method): ?self + { + /** @var self|null $self */ + if (!$self = ($method->getAttributes(self::class)[0] ?? null)?->newInstance()) { + return null; + } + + if (!$method->isPublic() || $method->isStatic()) { + throw new LogicException(\sprintf('The interactive method "%s::%s()" must be public and non-static.', $method->class, $method->getName())); + } + + if ('__invoke' === $method->getName()) { + throw new LogicException(\sprintf('The "%s::__invoke()" method cannot be used as an interactive method.', $method->class)); + } + + $self->method = $method; + + return $self; + } + + /** + * @internal + */ + public function getFunction(object $instance): \ReflectionFunction + { + return new \ReflectionFunction($this->method->getClosure($instance)); + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/InteractiveAttributeInterface.php b/trilhas_poo/vendor/symfony/console/Attribute/InteractiveAttributeInterface.php new file mode 100644 index 0000000..0b02d7d --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/InteractiveAttributeInterface.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * @internal + */ +interface InteractiveAttributeInterface +{ + public function getFunction(object $instance): \ReflectionFunction; +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/MapDateTime.php b/trilhas_poo/vendor/symfony/console/Attribute/MapDateTime.php new file mode 100644 index 0000000..9e2ac51 --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/MapDateTime.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +/** + * Defines how a DateTime parameter should be resolved from command input. + * + * @author Robin Chalas + */ +#[\Attribute(\Attribute::TARGET_PARAMETER)] +class MapDateTime +{ + /** + * @param string|null $format The DateTime format (@see https://php.net/datetime.format) + * @param string|null $argument The argument name to read from (defaults to parameter name) + * @param string|null $option The option name to read from (mutually exclusive with $argument) + */ + public function __construct( + public readonly ?string $format = null, + public readonly ?string $argument = null, + public readonly ?string $option = null, + ) { + if ($argument && $option) { + throw new \LogicException('MapDateTime cannot specify both argument and option.'); + } + } +} diff --git a/trilhas_poo/vendor/symfony/console/Attribute/MapInput.php b/trilhas_poo/vendor/symfony/console/Attribute/MapInput.php new file mode 100644 index 0000000..378937b --- /dev/null +++ b/trilhas_poo/vendor/symfony/console/Attribute/MapInput.php @@ -0,0 +1,250 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Console\Attribute; + +use Symfony\Component\Console\Attribute\Reflection\ReflectionMember; +use Symfony\Component\Console\Exception\LogicException; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Interaction\Interaction; + +/** + * Maps a command input into an object (DTO). + */ +#[\Attribute(\Attribute::TARGET_PARAMETER | \Attribute::TARGET_PROPERTY)] +final class MapInput +{ + /** + * @var array + */ + private array $definition = []; + + private \ReflectionClass $class; + + /** + * @var list + */ + private array $interactiveAttributes = []; + + /** + * @param string[]|null $validationGroups + */ + public function __construct( + public readonly ?array $validationGroups = null, + ) { + } + + /** + * @internal + */ + public static function tryFrom(\ReflectionParameter|\ReflectionProperty $member): ?self + { + $reflection = new ReflectionMember($member); + + if (!$self = $reflection->getAttribute(self::class)) { + return null; + } + + $type = $reflection->getType(); + + if (!$type instanceof \ReflectionNamedType) { + throw new LogicException(\sprintf('The input %s "%s" must have a named type.', $reflection->getMemberName(), $member->name)); + } + + if (!class_exists($class = $type->getName())) { + throw new LogicException(\sprintf('The input class "%s" does not exist.', $type->getName())); + } + + $self->class = new \ReflectionClass($class); + + foreach ($self->class->getProperties() as $property) { + if ($argument = Argument::tryFrom($property)) { + $self->definition[$property->name] = $argument; + } elseif ($option = Option::tryFrom($property)) { + $self->definition[$property->name] = $option; + } elseif ($input = self::tryFrom($property)) { + $self->definition[$property->name] = $input; + } + + if (isset($self->definition[$property->name]) && (!$property->isPublic() || $property->isStatic())) { + throw new LogicException(\sprintf('The input property "%s::$%s" must be public and non-static.', $self->class->name, $property->name)); + } + } + + if (!$self->definition) { + throw new LogicException(\sprintf('The input class "%s" must have at least one argument or option.', $self->class->name)); + } + + foreach ($self->class->getMethods() as $method) { + if ($attribute = Interact::tryFrom($method)) { + $self->interactiveAttributes[] = $attribute; + } + } + + return $self; + } + + /** + * @internal + */ + public function setValue(InputInterface $input, object $object): void + { + foreach ($this->definition as $name => $spec) { + $property = $this->class->getProperty($name); + + if (!$property->isInitialized($object) || \in_array($value = $property->getValue($object), [null, []], true)) { + continue; + } + + match (true) { + $spec instanceof Argument => $input->setArgument($spec->name, $value), + $spec instanceof Option => $input->setOption($spec->name, $value), + $spec instanceof self => $spec->setValue($input, $value), + default => throw new LogicException('Unexpected specification type.'), + }; + } + } + + /** + * @return iterable + */ + public function getArguments(): iterable + { + foreach ($this->definition as $spec) { + if ($spec instanceof Argument) { + yield $spec; + } elseif ($spec instanceof self) { + yield from $spec->getArguments(); + } + } + } + + /** + * @return iterable